package com.applozic.mobicomkit.uiwidgets.conversation.fragment;


import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.OpenableColumns;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.FileProvider;
import android.support.v4.os.AsyncTaskCompat;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.airbnb.lottie.LottieAnimationView;
import com.applozic.mobicomkit.ApplozicClient;
import com.applozic.mobicomkit.ChatConfig;
import com.applozic.mobicomkit.api.account.user.MobiComUserPreference;
import com.applozic.mobicomkit.api.account.user.UserBlockTask;
import com.applozic.mobicomkit.api.attachment.AttachmentView;
import com.applozic.mobicomkit.api.attachment.FileClientService;
import com.applozic.mobicomkit.api.attachment.FileMeta;
import com.applozic.mobicomkit.api.conversation.ApplozicMqttIntentService;
import com.applozic.mobicomkit.api.conversation.ConversationReadService;
import com.applozic.mobicomkit.api.conversation.Message;
import com.applozic.mobicomkit.api.conversation.MessageClientService;
import com.applozic.mobicomkit.api.conversation.MessageIntentService;
import com.applozic.mobicomkit.api.conversation.MobiComConversationService;
import com.applozic.mobicomkit.api.conversation.SyncCallService;
import com.applozic.mobicomkit.api.conversation.database.MessageDatabaseService;
import com.applozic.mobicomkit.api.conversation.selfdestruct.DisappearingMessageTask;
import com.applozic.mobicomkit.api.conversation.service.ConversationService;
import com.applozic.mobicomkit.api.notification.MuteNotificationAsync;
import com.applozic.mobicomkit.api.notification.MuteNotificationRequest;
import com.applozic.mobicomkit.api.people.UserIntentService;
import com.applozic.mobicomkit.broadcast.BroadcastService;
import com.applozic.mobicomkit.channel.service.ChannelService;
import com.applozic.mobicomkit.contact.AppContactService;
import com.applozic.mobicomkit.feed.ApiResponse;
import com.applozic.mobicomkit.uiwidgets.AlCustomizationSettings;
import com.applozic.mobicomkit.uiwidgets.attachmentview.ApplozicAudioManager;
import com.applozic.mobicomkit.uiwidgets.attachmentview.ApplozicAudioRecordManager;
import com.applozic.mobicomkit.uiwidgets.attachmentview.ApplozicDocumentView;
import com.applozic.mobicomkit.uiwidgets.conversation.ConversationListView;
import com.applozic.mobicomkit.uiwidgets.conversation.ConversationUIService;
import com.applozic.mobicomkit.uiwidgets.conversation.DeleteConversationAsyncTask;
import com.applozic.mobicomkit.uiwidgets.conversation.MessageCommunicator;
import com.applozic.mobicomkit.uiwidgets.conversation.activity.ConversationActivity;
import com.applozic.mobicomkit.uiwidgets.conversation.activity.MobiComKitActivityInterface;
import com.applozic.mobicomkit.uiwidgets.conversation.adapter.DetailedConversationAdapter;
import com.applozic.mobicomkit.uiwidgets.conversation.messageUtils.BubbleUtils;
import com.applozic.mobicomkit.uiwidgets.instruction.InstructionUtil;
import com.applozic.mobicomkit.uiwidgets.schedule.ScheduledTimeHolder;
import com.applozic.mobicommons.commons.core.utils.DateUtils;
import com.applozic.mobicommons.commons.core.utils.Support;
import com.applozic.mobicommons.commons.core.utils.Utils;
import com.applozic.mobicommons.commons.image.ImageCache;
import com.applozic.mobicommons.commons.image.ImageLoader;
import com.applozic.mobicommons.commons.image.ImageUtils;
import com.applozic.mobicommons.emoticon.EmojiconHandler;
import com.applozic.mobicommons.file.FileUtils;
import com.applozic.mobicommons.json.GsonUtils;
import com.applozic.mobicommons.people.channel.Channel;
import com.applozic.mobicommons.people.channel.ChannelUserMapper;
import com.applozic.mobicommons.people.channel.ChannelUtils;
import com.applozic.mobicommons.people.channel.Conversation;
import com.applozic.mobicommons.people.contact.Contact;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.ChooseLotteryActivity;
import com.lottery.ruok.lottrey.activity.ChooseManagerActivity;
import com.lottery.ruok.lottrey.activity.ChuantongcaiActivity;
import com.lottery.ruok.lottrey.activity.GetPacketResultActivity;
import com.lottery.ruok.lottrey.activity.LiuhecaiDetailActivity;
import com.lottery.ruok.lottrey.activity.NewChannelInfoActivity;
import com.lottery.ruok.lottrey.activity.OfficalLotteryDetailActivity;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.eventbusObject.BubbleChange;
import com.lottery.ruok.lottrey.eventbusObject.GivePrizeSuccess;
import com.lottery.ruok.lottrey.eventbusObject.GrabRedPacketSucess;
import com.lottery.ruok.lottrey.eventbusObject.PrizePushInfo;
import com.lottery.ruok.lottrey.eventbusObject.RedAniListener;
import com.lottery.ruok.lottrey.eventbusObject.SendRedPacketSuccess;
import com.lottery.ruok.lottrey.eventbusObject.StartPrzePush;
import com.lottery.ruok.lottrey.fragment.BaseFragment;
import com.lottery.ruok.lottrey.fragment.EmojiconsFragment;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetCurrentIssueNoRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetItemInfoRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetRoomUsersRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetWholeCategoryRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetCurrentIssueNoResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetItemInfoResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetRoomUsersResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetWholeCategoryResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.LotteryStatOneResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.Timer;
import java.util.concurrent.TimeUnit;

import count_down.CountDownManager;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import ui.AreaCircle;
import utils.StringUtils;

import static android.app.Activity.RESULT_OK;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static java.util.Collections.disjoint;

/**
 * reg
 * Created by devashish on 10/2/15.
 * 聊天页面聊天记录列表
 *fragment
 */
abstract public class MobiComConversationFragment extends BaseFragment implements View.OnClickListener, GestureDetector.OnGestureListener {
    public static final String ANALYTIC_VERSION = "1.0";

    //Todo: Increase the file size limit
    public static final int MAX_ALLOWED_FILE_SIZE = 10 * 1024 * 1024;
    private static final String TAG = "MobiComConversation";
    private static final int WHAT_ROOM_INFO = 111;
    private static int count;
    public FrameLayout emoticonsFrameLayout;
    //    public FrameLayout contextFrameLayout;
    public GridView multimediaPopupGrid;
    protected List<Conversation> conversations;
    protected DownloadConversation downloadConversation;
    protected MobiComConversationService conversationService;
    protected TextView infoBroadcast;
    protected Class messageIntentClass;
    protected TextView emptyTextView;
    protected boolean loadMore = true;
    protected Contact contact;
    protected Channel channel;
    protected Integer currentConversationId;
    protected EditText myMessageEditText;
    protected TextView myMessageRecord;
    protected ImageView mySendButton;
    protected ImageView myRecordButton;
    protected ImageView myKeyBoardButton;
    protected ImageView myAttachButton;
    protected ImageView myEmojiButton;
    protected LinearLayout mainEditTextLinearLayout;
    protected LinearLayout individualMessageSendLayout;
    protected RelativeLayout attachmentLayout;
    protected ProgressBar mediaUploadProgressBar;
    protected View spinnerLayout;
    protected SwipeRefreshLayout swipeLayout;
    protected ScheduledTimeHolder scheduledTimeHolder = new ScheduledTimeHolder();
    protected Spinner selfDestructMessageSpinner;
    protected ImageView mediaContainer;
    protected TextView attachedFile;
    protected String filePath;
    protected boolean firstTimeMTexterFriend;
    protected MessageCommunicator messageCommunicator;
    protected ConversationListView listView = null;
    protected List<Message> messageList = new ArrayList<>();
    protected DetailedConversationAdapter conversationAdapter = null;
    protected Drawable sentIcon;
    protected Drawable deliveredIcon;
    protected Support support;
    protected MultimediaOptionFragment multimediaOptionFragment = new MultimediaOptionFragment();
    protected boolean hideExtendedSendingOptionLayout;
    protected SyncCallService syncCallService;
    protected Message messageToForward;
    protected String searchString;
    protected AlCustomizationSettings alCustomizationSettings;
    List<ChannelUserMapper> channelUserMapperList;
    MessageDatabaseService messageDatabaseService;
    AppContactService appContactService;
    ConversationUIService conversationUIService;
    long millisecond;
    MuteNotificationRequest muteNotificationRequest;
    List<String> restrictedWords;
    FileClientService fileClientService;
    ImageLoader imageThumbnailLoader, messageImageLoader;
    ApplozicAudioRecordManager applozicAudioRecordManager;
    String timeStamp, audioFileName;
    String outputFile;
    GestureDetectorCompat mDetector;
    boolean longPress;
    int seconds = 0, minutes = 0;
    ApplozicDocumentView applozicDocumentView;
    private EmojiconHandler emojiIconHandler;
    private Bitmap previewThumbnail;
    private String defaultText;
    private boolean typingStarted;
    private Integer channelKey;
    private Menu menu;
    //    private Spinner contextSpinner;
    private boolean onSelected;
    private ImageCache imageCache;
    private float startedDraggingX = -1;
    WeakReference<ImageView> recordButtonWeakReference;
    private RelativeLayout lottery_area;
    private boolean isRunning = false;
    private TextView record_tip;
    private LottieAnimationView start_audio;
    float y1 = 0;
    float y2 = 0;
    private Disposable mSendRedPacketRunnable;
    private Runnable mGrabRedPacketRunnable;
    private Runnable mGivePrizeRunnable;
    private ImageView folder;
    private boolean isFirstIn = true;

    private LinearLayout lottery_type;
    private TextView lottery_type_text;
    private TextView time;
    private LinearLayout buy_layout;
    private LinearLayout containers;
    private ArrayList<GetWholeCategoryResponse> lotteryStatOneResponse;
    private ArrayList<LotteryStatOneResponse.ItemListBean> itemListBeans = new ArrayList<>();
    private Disposable disposable;
    private TextView prizing_text;

    private String mCurrentCode;
    private String mCurrentName;
    private int roomCount;
    private View bubbleTextView;
    private TextView bubbleText;
    private long voiceDuration;
    private GetCurrentIssueNoResponse lotteryData;
    private CountDownManager.CountDownModel countDownModel;

    public static int dp(float value) {
        return (int) Math.ceil(1 * value);
    }

    public void setEmojiIconHandler(EmojiconHandler emojiIconHandler) {
        this.emojiIconHandler = emojiIconHandler;
    }


    @Override
    public void onDestroy() {
        CountDownManager.asInstance().unRegister(countDownModel);
        super.onDestroy();

        if (mSendRedPacketRunnable != null) {
            mSendRedPacketRunnable.dispose();
            mSendRedPacketRunnable = null;
        }

        if (mGrabRedPacketRunnable != null) {
            myMessageEditText.removeCallbacks(mGrabRedPacketRunnable);
        }
        if (mGivePrizeRunnable != null) {
            myMessageEditText.removeCallbacks(mGivePrizeRunnable);
        }

        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RedAniListener event) {
        if (event.getConversationId() == null) {
            Intent intent = new Intent(getActivity(), GetPacketResultActivity.class);
            intent.putExtra(ChatConfig.PACKET_GET_ID, event.getGift_rand_id());
            intent.putExtra(ChatConfig.PACKET_ID, event.getGift_id());
            getContext().startActivity(intent);
        }
        if (event.getConversationId().equals(getActivity().getIntent().getStringExtra(ConversationUIService.USER_ID))) {
            Intent intent = new Intent(getActivity(), GetPacketResultActivity.class);
            intent.putExtra(ChatConfig.PACKET_GET_ID, event.getGift_rand_id());
            intent.putExtra(ChatConfig.PACKET_ID, event.getGift_id());
            getContext().startActivity(intent);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(final GivePrizeSuccess event) {
        mGivePrizeRunnable = new Runnable() {
            @Override
            public void run() {
                HashMap<String, String> messageMetaData = new HashMap<>();
                messageMetaData.put(ChatConfig.REWARD_FROM, UserInfo.getUsername());
                messageMetaData.put(ChatConfig.REWARD_TO, event.getUser_id());
                messageMetaData.put(ChatConfig.REWARD_MONEY, event.getAmount());
                messageMetaData.put(ChatConfig.FROM, UserInfo.getUsername());
                messageMetaData.put(ChatConfig.TYPE, ChatConfig.TYPE_GROUP);
                messageMetaData.put(ChatConfig.TO, channel.getKey() + "");
                messageMetaData.put(ChatConfig.REWARD_TIME, StringUtils.formatTime(System.currentTimeMillis(), ChatConfig.TIME_FORMAT));
                sendMessage("", messageMetaData, null, null, Message.ContentType.GIVE_PRIZE.getValue());
            }
        };
        myMessageEditText.postDelayed(mGivePrizeRunnable, 1000);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(final GrabRedPacketSucess event) {
        if (event.getConversationId() == null) {
            mGrabRedPacketRunnable = new Runnable() {
                @Override
                public void run() {
                    HashMap<String, String> messageMetaData = new HashMap<>();
                    messageMetaData.put(ChatConfig.FROM, UserInfo.getUsername());
                    messageMetaData.put(ChatConfig.TYPE, ChatConfig.TYPE_GROUP);
                    messageMetaData.put(ChatConfig.TO, channel.getKey() + "");
                    messageMetaData.put(ChatConfig.PACKET_FROM, event.getRedPacketFrom());
                    messageMetaData.put(ChatConfig.PACKET_TO, UserInfo.getUsername());
                    messageMetaData.put(ChatConfig.PACKET_ID, event.getRedPacketID());
                    messageMetaData.put(ChatConfig.PACKET_GET_ID, event.getHave_get_packet_id());
                    sendMessage("", messageMetaData, null, null, Message.ContentType.RED_PACKET_RESPONSE.getValue());
                }
            };
            myMessageEditText.postDelayed(mGrabRedPacketRunnable, 1000);
        } else if (event.getConversationId().equals(getActivity().getIntent().getStringExtra(ConversationUIService.USER_ID))) {
            mGrabRedPacketRunnable = new Runnable() {
                @Override
                public void run() {

                    HashMap<String, String> messageMetaData = new HashMap<>();
                    messageMetaData.put(ChatConfig.FROM, UserInfo.getUsername());
                    messageMetaData.put(ChatConfig.TYPE, ChatConfig.TYPE_USER);
                    messageMetaData.put(ChatConfig.TO, channelKey + "");
                    messageMetaData.put(ChatConfig.PACKET_FROM, event.getRedPacketFrom());
                    messageMetaData.put(ChatConfig.PACKET_TO, UserInfo.getUsername());
                    messageMetaData.put(ChatConfig.PACKET_ID, event.getRedPacketID());
                    messageMetaData.put(ChatConfig.PACKET_GET_ID, event.getHave_get_packet_id());
                    sendMessage("", messageMetaData, null, null, Message.ContentType.RED_PACKET_RESPONSE.getValue());
                }
            };
            myMessageEditText.postDelayed(mGrabRedPacketRunnable, 1000);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(final SendRedPacketSuccess event) {
        if (event.getConversationId() == null) {
            mSendRedPacketRunnable = Observable.timer(1, TimeUnit.SECONDS)
                    .subscribe(new Consumer<Long>() {
                            @Override
                        public void accept(Long aLong) {
                            HashMap<String, String> messageMetaData = new HashMap<>();
                            messageMetaData.put(ChatConfig.FROM, UserInfo.getUsername());
                            messageMetaData.put(ChatConfig.TO, channelKey + "");
                            messageMetaData.put(ChatConfig.TYPE, ChatConfig.TYPE_GROUP);
                            messageMetaData.put(ChatConfig.PACKET_FROM, UserInfo.getUsername());
                            messageMetaData.put(ChatConfig.PACKET_TYPE, event.getPacketType() + "");
                            messageMetaData.put(ChatConfig.PACKET_TO, "");
                            messageMetaData.put(ChatConfig.PACKET_ID, event.getPacketId());
                            messageMetaData.put(ChatConfig.PACKET_MESSAGE, event.getContent());
                            sendMessage("", messageMetaData, null, null, Message.ContentType.RED_PACKET.getValue());
                        }
                    });
        } else if (event.getConversationId().equals(getActivity().getIntent().getStringExtra(ConversationUIService.USER_ID))) {
            mSendRedPacketRunnable = Observable.timer(1, TimeUnit.SECONDS)
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) {
                            HashMap<String, String> messageMetaData = new HashMap<>();
                            messageMetaData.put(ChatConfig.FROM, UserInfo.getUsername());
                            messageMetaData.put(ChatConfig.TO, channelKey + "");
                            messageMetaData.put(ChatConfig.TYPE, ChatConfig.TYPE_USER);
                            messageMetaData.put(ChatConfig.PACKET_FROM, UserInfo.getUsername());
                            messageMetaData.put(ChatConfig.PACKET_TYPE, event.getPacketType() + "");
                            messageMetaData.put(ChatConfig.PACKET_TO, event.getConversationId());
                            messageMetaData.put(ChatConfig.PACKET_ID, event.getPacketId());
                            messageMetaData.put(ChatConfig.PACKET_MESSAGE, event.getContent());
                            sendMessage("", messageMetaData, null, null, Message.ContentType.RED_PACKET.getValue());
                        }
                    });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PrizePushInfo event) {
        if (event.getCode() != null && mCurrentCode != null) {
            if (event.getCode().equals(mCurrentCode) || ("ct" + event.getCode()).equals(mCurrentCode)) {
                getPrizeInfo(mCurrentCode, mCurrentName);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(StartPrzePush event) {
        getCurrentIssueNo();
        getPrizeInfo(mCurrentCode, mCurrentName);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);

        String jsonString = FileUtils.loadSettingsJsonFile(getActivity().getApplicationContext());
        if (!TextUtils.isEmpty(jsonString)) {
            alCustomizationSettings = (AlCustomizationSettings) GsonUtils.getObjectFromJson(jsonString, AlCustomizationSettings.class);
        } else {
            alCustomizationSettings = new AlCustomizationSettings();
        }
        applozicDocumentView = new ApplozicDocumentView(getContext());
        restrictedWords = FileUtils.loadRestrictedWordsFile(getContext());
        conversationUIService = new ConversationUIService(getActivity());
        syncCallService = SyncCallService.getInstance(getActivity());
        appContactService = new AppContactService(getActivity());
        messageDatabaseService = new MessageDatabaseService(getActivity());
        fileClientService = new FileClientService(getActivity());
        setHasOptionsMenu(false);
        imageThumbnailLoader = new ImageLoader(getContext(), ImageUtils.getLargestScreenDimension((Activity) getContext())) {
            @Override
            protected Bitmap processBitmap(Object data) {
                return fileClientService.loadThumbnailImage(getContext(), (Message) data, getImageLayoutParam(false).width, getImageLayoutParam(false).height);
            }
        };

        imageCache = ImageCache.getInstance((getActivity()).getSupportFragmentManager(), 0.1f);
        imageThumbnailLoader.setImageFadeIn(false);
        imageThumbnailLoader.addImageCache((getActivity()).getSupportFragmentManager(), 0.1f);
        messageImageLoader = new ImageLoader(getContext(), ImageUtils.getLargestScreenDimension((Activity) getContext())) {
            @Override
            protected Bitmap processBitmap(Object data) {
                return fileClientService.loadMessageImage(getContext(), (String) data);
            }
        };
        messageImageLoader.setImageFadeIn(false);
        messageImageLoader.addImageCache((getActivity()).getSupportFragmentManager(), 0.1f);
        applozicAudioRecordManager = new ApplozicAudioRecordManager(getActivity());
        mDetector = new GestureDetectorCompat(getContext(), this);

        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {//判断是否拥有录音的权限
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.RECORD_AUDIO}, 10);
        }
        getRoomInfo();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 100 && resultCode == RESULT_OK) {
            if (disposable != null) {
                disposable.dispose();
            }
            mCurrentCode = data.getStringExtra("code");
            mCurrentName = data.getStringExtra("name");
            getCurrentIssueNo();
            getPrizeInfo(mCurrentCode, mCurrentName);
        }
    }

    private void getPrizeInfo(final String code, final String name) {
        disposable = RetrofitBase.getRetrofit().create(GetItemInfoRequest.class)
                .getResult(code)
                .compose(RxHelper.<GetItemInfoResponse>handleResult())
                .subscribeWith(new RxSubscribe<GetItemInfoResponse>(getActivity()) {
                    @Override
                    protected void _onNext(final GetItemInfoResponse getItemInfoResponse) {
                        if (getActivity() != null) {
                            if (!lottery_type_text.getText().toString().equals(name)) {
                                lottery_type_text.setText(name);
                            }

                            lottery_type.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (lotteryStatOneResponse != null) {
                                        Intent intent = new Intent(getActivity(), ChooseLotteryActivity.class);
                                        intent.putParcelableArrayListExtra("lists", itemListBeans);
                                        intent.putExtra("code", code);
                                        startActivityForResult(intent, 100);
                                        getActivity().overridePendingTransition(R.anim.anim_enter_from_bottom, R.anim.activity_stay);
                                    }
                                }
                            });

                            buy_layout.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    //sendAnalyticMsg("lottery" + ANALYTIC_VERSION + "_chat_lottery_" + code + "_buy_jump");
                                    switch (getItemInfoResponse.getData().getItem_class()) {
                                        case 1: {
                                            Intent intent = new Intent(getActivity(), OfficalLotteryDetailActivity.class);
                                            intent.putExtra("code", code);
                                            startActivity(intent);
                                            break;
                                        }
                                        case 2: {
                                            Intent intent = new Intent(getActivity(), LiuhecaiDetailActivity.class);
                                            intent.putExtra("code", code);
                                            startActivity(intent);
                                            break;
                                        }
                                        case 3: {
                                            Intent intent = new Intent(getActivity(), ChuantongcaiActivity.class);
                                            intent.putExtra("code", code);
                                            startActivity(intent);
                                            break;
                                        }
                                    }
                                }
                            });

                            if (code.equals("xglhc") || code.equals("jslhc") || code.equals("js10flhc")) {//香港六合彩开奖特殊情况
                                String[] p = getItemInfoResponse.getData().getPrize_num().split(",");
                                if (p != null && p.length > 0 && !p[0].equals("")) {
                                    containers.removeAllViews();
                                    containers.setVisibility(VISIBLE);
                                    prizing_text.setVisibility(View.INVISIBLE);
                                    for (int i = 0; i < p.length; i++) {
                                        TextView areaCircle = new TextView(getActivity().getApplicationContext());
                                        switch (getItemInfoResponse.getAttached().getColor().get(i)) {
                                            case "green":
                                                areaCircle.setBackgroundResource(R.mipmap.green_big);
                                                break;
                                            case "red":
                                                areaCircle.setBackgroundResource(R.mipmap.red_big);
                                                break;
                                            case "blue":
                                                areaCircle.setBackgroundResource(R.mipmap.blue_big);
                                                break;
                                        }
                                        areaCircle.setTextColor(getResources().getColor(R.color.lottery_black));
                                        areaCircle.setGravity(Gravity.CENTER);
                                        areaCircle.setText(p[i]);
                                        areaCircle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
                                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(utils.Utils.dip2px(getActivity().getApplicationContext(), 20), utils.Utils.dip2px(getActivity().getApplicationContext(), 20));
                                        layoutParams.rightMargin = utils.Utils.dip2px(getActivity().getApplicationContext(), 6);
                                        layoutParams.gravity = Gravity.CENTER;
                                        areaCircle.setLayoutParams(layoutParams);
                                        containers.addView(areaCircle);
                                    }
                                } else {
                                    containers.setVisibility(View.INVISIBLE);
                                    prizing_text.setVisibility(VISIBLE);
                                }
                            } else {
                                String[] p = getItemInfoResponse.getData().getPrize_num().split(",");
                                if (p != null && p.length > 0 && !p[0].equals("")) {
                                    containers.setVisibility(VISIBLE);
                                    prizing_text.setVisibility(View.INVISIBLE);
                                    containers.removeAllViews();
                                    for (String s : p) {
                                        AreaCircle areaCircle = new AreaCircle(getActivity().getApplicationContext());
                                        Common.setBallBackground(areaCircle, s, code);

                                        areaCircle.setText(s);
                                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(utils.Utils.dip2px(getActivity().getApplicationContext(), 20), utils.Utils.dip2px(getActivity().getApplicationContext(), 20));
                                        layoutParams.rightMargin = utils.Utils.dip2px(getActivity().getApplicationContext(), 6);
                                        areaCircle.setLayoutParams(layoutParams);
                                        containers.addView(areaCircle);
                                    }
                                } else {
                                    containers.setVisibility(View.INVISIBLE);
                                    prizing_text.setVisibility(VISIBLE);
                                }
                            }
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    /**
     * 获取当前 菜种信息
     */
    private void getCurrentIssueNo() {
        RetrofitBase.getRetrofit().create(GetCurrentIssueNoRequest.class).getResult(mCurrentCode)
                .compose(RxHelper.<GetCurrentIssueNoResponse>handleResultReConnection())
                .subscribe(new RxSubscribe<GetCurrentIssueNoResponse>(getActivity()) {
                    @Override
                    protected void _onNext(GetCurrentIssueNoResponse getCurrentIssueNoResponse) {
                        lotteryData = getCurrentIssueNoResponse;
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(final BubbleChange event) {
        autoShowBubbleText(event.getUserName());
    }

    private void autoShowBubbleText(String userName) {
        if (utils.Utils.isEmpty(userName)) {
            if (bubbleTextView != null) {
                bubbleTextView.setVisibility(GONE);
            }
            return;
        }
        boolean is_single = getActivity().getIntent().getBooleanExtra("is_single", false);
        if (is_single) {
            if (bubbleTextView != null) {
                bubbleTextView.setVisibility(GONE);
            }
        } else {
            if (BubbleUtils.getTotalNum() > 0) {
                if (bubbleTextView != null) {
                    int chatroom_role = UserInfo.getChatroom_role();
                    if (chatroom_role == 1) {
                        bubbleText.setText("管理员" + userName + "向你发起了对话");
                    } else {
                        bubbleText.setText("会员" + userName + "向你发起了对话");
                    }
                    bubbleTextView.setVisibility(VISIBLE);
                }
            } else {
                if (bubbleTextView != null) {
                    bubbleTextView.setVisibility(GONE);
                }
            }
        }
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View list = inflater.inflate(R.layout.mobicom_message_list, container, false);

        bubbleTextView = list.findViewById(R.id.view_bubble_text);
        bubbleText = list.findViewById(R.id.tv_bubble_text);
        autoShowBubbleText(BubbleUtils.getKey());
        bubbleTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UserInfo.getChatroom_role() != 1) {//管理员
                    Intent intent = new Intent(getActivity(), NewChannelInfoActivity.class);
                    startActivity(intent);
                } else {//管理员列表界面
                    Intent intent = new Intent(getActivity(), ChooseManagerActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.anim_enter_from_bottom, R.anim.activity_stay);
                }
            }
        });
        lottery_type = list.findViewById(R.id.lottery_type);
        lottery_type_text = list.findViewById(R.id.lottery_type_text);
        time = list.findViewById(R.id.time);
        buy_layout = list.findViewById(R.id.buy_layout);
        containers = list.findViewById(R.id.container);
        prizing_text = list.findViewById(R.id.prizing_text);
        mCurrentCode = "bjpk10";
        mCurrentName = "北京赛车";
        getPrizeInfo(mCurrentCode, mCurrentName);
        countDown();
        getCurrentIssueNo();
        RetrofitBase.getRetrofit().create(GetWholeCategoryRequest.class).getResult(UserInfo.getToken(), 0, 0)
                .compose(RxHelper.<ArrayList<GetWholeCategoryResponse>>handleResult())
                .subscribe(new RxSubscribe<ArrayList<GetWholeCategoryResponse>>(getActivity()) {
                    @Override
                    protected void _onNext(ArrayList<GetWholeCategoryResponse> getWholeCategoryResponses) {
                        lotteryStatOneResponse = getWholeCategoryResponses;

                        for (GetWholeCategoryResponse getWholeCategoryResponse : lotteryStatOneResponse) {
                            if (getWholeCategoryResponse.getName().equals("全部")) {
                                lotteryStatOneResponse.remove(getWholeCategoryResponse);
                                break;
                            }
                            LotteryStatOneResponse.ItemListBean itemListBean = new LotteryStatOneResponse.ItemListBean();
                            itemListBean.setNameX(getWholeCategoryResponse.getName());
                            itemListBean.setItems(new ArrayList<LotteryStatOneResponse.ItemListBean.ItemsBean>());
                            for (GetWholeCategoryResponse.ItemsBean itemsBean : getWholeCategoryResponse.getItems()) {
                                LotteryStatOneResponse.ItemListBean.ItemsBean itemsBean1 = new LotteryStatOneResponse.ItemListBean.ItemsBean();
                                itemsBean1.setNameX(itemsBean.getName());
                                itemsBean1.setCode(itemsBean.getCode());
                                itemListBean.getItems().add(itemsBean1);
                            }
                            itemListBeans.add(itemListBean);
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });

        folder = list.findViewById(R.id.fold);
        lottery_area = list.findViewById(R.id.lottery_area);
        isRunning = false;

        listView = list.findViewById(R.id.messageList);
        ((ConversationActivity) getActivity()).setChildFragmentLayoutBGToTransparent();
        listView.setDivider(null);
        messageList = new ArrayList<>();
        multimediaPopupGrid = list.findViewById(R.id.mobicom_multimedia_options1);

        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        mainEditTextLinearLayout = list.findViewById(R.id.main_edit_text_linear_layout);
        individualMessageSendLayout = list.findViewById(R.id.individual_message_send_layout);
        mySendButton = individualMessageSendLayout.findViewById(R.id.conversation_send);
        myRecordButton = individualMessageSendLayout.findViewById(R.id.record_button);
        myKeyBoardButton = individualMessageSendLayout.findViewById(R.id.keyboard_button);
        record_tip = list.findViewById(R.id.record_tip);
        start_audio = list.findViewById(R.id.start_audio);
        Configuration config = getResources().getConfiguration();
        recordButtonWeakReference = new WeakReference<>(myRecordButton);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (config.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
                mySendButton.setScaleX(-1);
                mainEditTextLinearLayout.setBackgroundResource(R.drawable.applozic_chat_left_icon);
            }
        }

        attachmentLayout = list.findViewById(R.id.attachment_layout);

        mDetector = new GestureDetectorCompat(getContext(), this);

        mediaUploadProgressBar = attachmentLayout.findViewById(R.id.media_upload_progress_bar);
        emoticonsFrameLayout = list.findViewById(R.id.emojicons_frame_layout);
        spinnerLayout = inflater.inflate(R.layout.mobicom_message_list_header_footer, null);
        infoBroadcast = spinnerLayout.findViewById(R.id.info_broadcast);
        spinnerLayout.setVisibility(GONE);
        emptyTextView = list.findViewById(R.id.noConversations);
        emptyTextView.setTextColor(Color.parseColor(alCustomizationSettings.getNoConversationLabelTextColor().trim()));
        listView.addHeaderView(spinnerLayout);
        sentIcon = getResources().getDrawable(R.drawable.applozic_ic_action_message_sent);
        deliveredIcon = getResources().getDrawable(R.drawable.applozic_ic_action_message_delivered);

        listView.setLongClickable(true);

        myRecordButton.setVisibility(alCustomizationSettings.isRecordButton() ? View.VISIBLE : GONE);
        mySendButton.setVisibility(alCustomizationSettings.isRecordButton() ? GONE : View.VISIBLE);

        myAttachButton = individualMessageSendLayout.findViewById(R.id.attach_buttons);
        myEmojiButton = individualMessageSendLayout.findViewById(R.id.emoji_button);
        myEmojiButton.setOnClickListener(this);

        myMessageEditText = individualMessageSendLayout.findViewById(R.id.conversation_message);
        myMessageRecord = individualMessageSendLayout.findViewById(R.id.conversation_message_record);

        myMessageEditText.setTextColor(Color.parseColor(alCustomizationSettings.getMessageEditTextTextColor()));

        myMessageEditText.setHintTextColor(Color.parseColor(alCustomizationSettings.getMessageEditTextHintTextColor()));

        if (!TextUtils.isEmpty(defaultText)) {
            myMessageEditText.setText(defaultText);
            defaultText = "";
        }
        mediaContainer = attachmentLayout.findViewById(R.id.media_container);
        attachedFile = attachmentLayout.findViewById(R.id.attached_file);
        ImageView closeAttachmentLayout = attachmentLayout.findViewById(R.id.close_attachment_layout);

        swipeLayout = list.findViewById(R.id.swipe_container);
        swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        listView.setMessageEditText(myMessageEditText);

        myMessageRecord.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mDetector.onTouchEvent(motionEvent);
                if (!UserInfo.getToken().equals("")) {
                    if (motionEvent.getAction() == MotionEvent.ACTION_UP && longPress) {
                        if (y1 - y2 <= Utils.dpToPx(50)) {
                            applozicAudioRecordManager.sendAudio();
                            myMessageEditText.requestFocus();
                            seconds = 0;
                            minutes = 0;
                            count = 0;
                        } else {
                            applozicAudioRecordManager.cancelAudio();
                        }
                        longPress = false;
                        myMessageRecord.setText("按住说话");
                        utils.Utils.muteAudioFocus(getContext(), false);
                        start_audio.setVisibility(GONE);
                        record_tip.setVisibility(GONE);
                        mainEditTextLinearLayout.setBackgroundResource(R.drawable.bg_corners_chat);

                        y1 = 0;
                        y2 = 0;
                    } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE && longPress) {
                        y2 = motionEvent.getY();
                        if (y1 - y2 > Utils.dpToPx(50)) {
                            record_tip.setVisibility(VISIBLE);
                            start_audio.setVisibility(GONE);
                        } else {
                            record_tip.setVisibility(GONE);
                            start_audio.setVisibility(VISIBLE);
                        }
                    } else if (motionEvent.getAction() == MotionEvent.ACTION_DOWN && longPress) {
                        y1 = motionEvent.getY();
                    }
                }
                view.onTouchEvent(motionEvent);
                return true;
            }
        });


        myMessageEditText.addTextChangedListener(new TextWatcher() {

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // EmojiconHandler.addEmojis(getActivity(), myMessageEditText.getText(), Utils.dpToPx(30));
                //TODO: write code to emoticons .....

            }

            public void afterTextChanged(Editable s) {
                try {
                    if (!TextUtils.isEmpty(s.toString()) && s.toString().trim().length() > 0 && !typingStarted) {
                        //Log.i(TAG, "typing started event...");
                        typingStarted = true;
                        handleSendAndRecordButtonView(true);
                        Intent intent = new Intent(getActivity(), ApplozicMqttIntentService.class);
                        intent.putExtra(ApplozicMqttIntentService.CHANNEL, channel);
                        intent.putExtra(ApplozicMqttIntentService.CONTACT, contact);
                        intent.putExtra(ApplozicMqttIntentService.TYPING, typingStarted);
                        getActivity().startService(intent);
                    } else if (s.toString().trim().length() == 0 && typingStarted) {
                        //Log.i(TAG, "typing stopped event...");
                        typingStarted = false;
                        handleSendAndRecordButtonView(false);
                        Intent intent = new Intent(getActivity(), ApplozicMqttIntentService.class);
                        intent.putExtra(ApplozicMqttIntentService.CHANNEL, channel);
                        intent.putExtra(ApplozicMqttIntentService.CONTACT, contact);
                        intent.putExtra(ApplozicMqttIntentService.TYPING, typingStarted);
                        getActivity().startService(intent);
                    }

                } catch (Exception e) {

                }
            }
        });

        myMessageEditText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                emoticonsFrameLayout.setVisibility(GONE);
            }
        });


        myMessageEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (typingStarted) {
                        Intent intent = new Intent(getActivity(), ApplozicMqttIntentService.class);
                        intent.putExtra(ApplozicMqttIntentService.CHANNEL, channel);
                        intent.putExtra(ApplozicMqttIntentService.CONTACT, contact);
                        intent.putExtra(ApplozicMqttIntentService.TYPING, typingStarted);
                        getActivity().startService(intent);
                    }
                    emoticonsFrameLayout.setVisibility(GONE);

                    multimediaPopupGrid.setVisibility(GONE);
                }
            }

        });

        myMessageEditText.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                        (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    Utils.toggleSoftKeyBoard(getActivity(), true);
                    return true;
                }
                return false;
            }
        });

        myKeyBoardButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myRecordButton.setVisibility(VISIBLE);
                myKeyBoardButton.setVisibility(GONE);

                myMessageRecord.setVisibility(GONE);
                myMessageEditText.setVisibility(VISIBLE);
            }
        });

        myRecordButton.setOnClickListener(new View.OnClickListener() {
                                              @Override
                                              public void onClick(View view) {
                                                  myMessageRecord.setVisibility(VISIBLE);
                                                  myMessageEditText.setVisibility(GONE);

                                                  myRecordButton.setVisibility(GONE);
                                                  myKeyBoardButton.setVisibility(VISIBLE);
                                              }
                                          }
        );

        mySendButton.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_chat_face_send");

                                                if (!UserInfo.getToken().equals("")) {
                                                    if (Common.fobid_words != null) {
                                                        for (String s : Common.fobid_words) {
                                                            if (myMessageEditText.getText().toString().contains(s)) {
                                                                utils.Utils.showToast("请不要包含敏感词:" + s);
                                                                return;
                                                            }
                                                        }
                                                    }

                                                    emoticonsFrameLayout.setVisibility(GONE);
                                                    sendMessage();
                                                    if (contact != null && !contact.isBlocked() || channel != null) {
                                                        handleSendAndRecordButtonView(false);
                                                    }
                                                } else {
                                                    gotoLoginActivity();
                                                }
                                            }
                                        }
        );


        closeAttachmentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                filePath = null;
                if (previewThumbnail != null) {
                    previewThumbnail.recycle();
                }
                attachmentLayout.setVisibility(GONE);
            }
        });

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
                                         @Override
                                         public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                                             if (conversationAdapter != null) {
                                                 conversationAdapter.contactImageLoader.setPauseWork(scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING);
                                             }
                                         }

                                         @Override
                                         public void onScroll(AbsListView view, int firstVisibleItem, int amountVisible,
                                                              int totalItems) {
                                             if (loadMore) {
                                                 int topRowVerticalPosition =
                                                         (listView == null || listView.getChildCount() == 0) ?
                                                                 0 : listView.getChildAt(0).getTop();
                                                 swipeLayout.setEnabled(topRowVerticalPosition >= 0);
                                             }
                                         }
                                     }
        );

        EmojiconsFragment emojiFragment = new EmojiconsFragment();
        emojiFragment.setEditText(myMessageEditText);
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.add(R.id.emojicons_frame_layout, emojiFragment).commit();
        return list;
    }

    private void countDown() {
        countDownModel = new CountDownManager.CountDownModel() {

            private boolean isLoad;

            @Override
            public void onExecute() {
                if (lotteryData != null) {
                    lotteryData.setTime(lotteryData.getTime() - 1);
                    if (lotteryData.getTime() >= 0) {
                        isLoad = false;
                        if (time != null) {
                            time.setText(utils.Utils.getCountTimeByLong(lotteryData.getTime() * 1000));
                        }
                    } else {
                        //加载数据
                        if (!isLoad && getActivity() != null) {
                            isLoad = true;
                            if (containers != null) {
                                containers.setVisibility(View.INVISIBLE);
                            }
                            if (prizing_text != null) {
                                prizing_text.setVisibility(VISIBLE);
                            }

                            getCurrentIssueNo();
                            getPrizeInfo(mCurrentCode, mCurrentName);
                        }
                    }
                }
            }
        };
        CountDownManager.asInstance().register(countDownModel);
    }

    public void handleSendAndRecordButtonView(boolean isSendButtonVisible) {
        mySendButton.setVisibility(alCustomizationSettings.isRecordButton() ? isSendButtonVisible ? View.VISIBLE : GONE : View.VISIBLE);
        myAttachButton.setVisibility(alCustomizationSettings.isRecordButton() ? isSendButtonVisible ? GONE : View.VISIBLE : GONE);
    }

    @Override
    public boolean onFling(MotionEvent event1, MotionEvent event2,
                           float velocityX, float velocityY) {
        return true;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
                            float distanceY) {
        return true;
    }

    @Override
    public boolean onSingleTapUp(MotionEvent event) {
        return true;
    }


    @Override
    public void onShowPress(MotionEvent event) {
    }

    @Override
    public boolean onDown(MotionEvent event) {
        return true;
    }

    @Override
    public void onLongPress(MotionEvent event) {

        if (!UserInfo.getToken().equals("")) {
            if (contact != null && contact.isBlocked()) {
                userBlockDialog(false, contact, false);
                return;
            }
            if (ApplozicAudioManager.getInstance(getContext()) != null) {
                ApplozicAudioManager.getInstance(getContext()).audiostop();
            }
            startedDraggingX = -1;
            ViewConfiguration.getLongPressTimeout();
            timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            audioFileName = "AUD_" + timeStamp + "_" + ".wav";
            outputFile = FileClientService.getFilePath(audioFileName, getContext().getApplicationContext(), "audio/wav").getAbsolutePath();
            applozicAudioRecordManager.setTimeStamp(timeStamp);
            applozicAudioRecordManager.setAudioFileName(audioFileName);
            applozicAudioRecordManager.setOutputFile(outputFile);
            vibrate();
            if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.RECORD_AUDIO}, 10);
            } else {
                applozicAudioRecordManager.recordAudio();
            }
            myRecordButton.getParent()
                    .requestDisallowInterceptTouchEvent(true);
            myMessageRecord.setText("松开发送");
            record_tip.setVisibility(GONE);
            start_audio.setVisibility(VISIBLE);
            mainEditTextLinearLayout.setBackgroundResource(R.drawable.bg_corners_chat_press);
            longPress = true;

            utils.Utils.muteAudioFocus(getContext(), true);
        } else {
            gotoLoginActivity();
        }
    }

    private void vibrate() {
        try {
            Vibrator v = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(200);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void sendMessage() {
        if (channel != null) {
            if (Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType())) {
                String userId = ChannelService.getInstance(getActivity()).getGroupOfTwoReceiverUserId(channel.getKey());
                if (!TextUtils.isEmpty(userId)) {
                    Contact withUserContact = appContactService.getContactById(userId);
                    if (withUserContact.isBlocked()) {
                        userBlockDialog(false, withUserContact, true);
                    } else {
                        processSendMessage();
                    }
                }
            } else if (Channel.GroupType.OPEN.getValue().equals(channel.getType())) {
                if (Utils.isInternetAvailable(getActivity())) {
                    processSendMessage();
                } else {
                    Toast.makeText(getActivity(), getActivity().getString(R.string.internet_connection_not_available), Toast.LENGTH_SHORT).show();
                }
            } else {
                processSendMessage();
            }
        } else if (contact != null) {
            if (contact.isBlocked()) {
                userBlockDialog(false, contact, false);
            } else {
                processSendMessage();
            }
        }
    }

    protected void processSendMessage() {
        if (!TextUtils.isEmpty(myMessageEditText.getText().toString().trim()) || !TextUtils.isEmpty(filePath)) {
            String inputMessage = myMessageEditText.getText().toString();
            String[] inputMsg = inputMessage.toLowerCase().split(" ");
            List<String> userInputList = Arrays.asList(inputMsg);

            boolean disjointResult = (restrictedWords == null) || disjoint(restrictedWords, userInputList);

            if (disjointResult) {
                sendMessage(myMessageEditText.getText().toString().trim(), null);
                myMessageEditText.setText("");
                if (scheduledTimeHolder.getTimestamp() != null) {
                    showScheduleMessageToast();
                }
                scheduledTimeHolder.resetScheduledTimeHolder();

            } else {
                final AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity()).
                        setPositiveButton(R.string.ok_alert, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        });
                alertDialog.setTitle(alCustomizationSettings.getRestrictedWordMessage());
                alertDialog.setCancelable(true);
                alertDialog.create().show();

            }
        }

    }

    public void showScheduleMessageToast() {
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(getActivity(), R.string.info_message_scheduled, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void deleteMessageFromDeviceList(String messageKeyString) {
        try {
            int position;
            boolean updateQuickConversation = false;
            int index;
            for (Message message : messageList) {
                boolean value = message.getKeyString() != null && message.getKeyString().equals(messageKeyString);
                if (value) {
                    index = messageList.indexOf(message);
                    if (index != -1) {
                        int aboveIndex = index - 1;
                        int belowIndex = index + 1;
                        Message aboveMessage = messageList.get(aboveIndex);
                        if (belowIndex != messageList.size()) {
                            Message belowMessage = messageList.get(belowIndex);
                            if (aboveMessage.isTempDateType() && belowMessage.isTempDateType()) {
                                messageList.remove(aboveMessage);
                            }
                        } else if (belowIndex == messageList.size() && aboveMessage.isTempDateType()) {
                            messageList.remove(aboveMessage);
                        }
                    }
                }
                if (message.getKeyString() != null && message.getKeyString().equals(messageKeyString)) {
                    position = messageList.indexOf(message);

                    if (position == messageList.size() - 1) {
                        updateQuickConversation = true;
                    }
                    if (message.getScheduledAt() != null && message.getScheduledAt() != 0) {
                        messageDatabaseService.deleteScheduledMessage(messageKeyString);
                    }
                    messageList.remove(position);
                    conversationAdapter.notifyDataSetChanged();
                    if (messageList.isEmpty()) {
                        emptyTextView.setVisibility(VISIBLE);
                        ((MobiComKitActivityInterface) getActivity()).removeConversation(message, channel != null ? String.valueOf(channel.getKey()) : contact.getFormattedContactNumber());
                    }
                    break;
                }
            }
            int messageListSize = messageList.size();
            if (messageListSize > 0 && updateQuickConversation) {
                ((MobiComKitActivityInterface) getActivity()).updateLatestMessage(messageList.get(messageListSize - 1), channel != null ? String.valueOf(channel.getKey()) : contact.getFormattedContactNumber());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public String getCurrentUserId() {
        if (contact == null) {
            return "";
        }
        return contact.getUserId() != null ? contact.getUserId() : contact.getFormattedContactNumber();
    }

    public Contact getContact() {
        return contact;
    }

    protected void setContact(Contact contact) {
        this.contact = contact;
    }

    public String getFormattedContactNumber() {
        return contact != null ? contact.getFormattedContactNumber() : null;
    }

    public boolean hasMultiplePhoneNumbers() {
        return contact != null && contact.hasMultiplePhoneNumbers();
    }

    public MultimediaOptionFragment getMultimediaOptionFragment() {
        return multimediaOptionFragment;
    }


    public Spinner getSelfDestructMessageSpinner() {
        return selfDestructMessageSpinner;
    }



    public void setFirstTimeMTexterFriend(boolean firstTimeMTexterFriend) {
        this.firstTimeMTexterFriend = firstTimeMTexterFriend;
    }

    public void clearList() {
        this.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (conversationAdapter != null) {
                    messageList.clear();
                    conversationAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    public void updateMessage(final Message message) {
        this.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //Note: Removing and adding the same message again as the new sms object will contain the keyString.
                messageList.remove(message);
                messageList.add(message);
                conversationAdapter.notifyDataSetChanged();
            }
        });
    }

    public void addMessage(final Message message) {
        this.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //Todo: Handle disappearing messages.
                boolean added = updateMessageList(message, false);
                if (added) {
                    //Todo: update unread count
                    conversationAdapter.notifyDataSetChanged();
                    listView.smoothScrollToPosition(messageList.size());
                    listView.setSelection(messageList.size());
                    emptyTextView.setVisibility(GONE);
                    currentConversationId = message.getConversationId();
                    channelKey = message.getGroupId();
                    if (Message.MessageType.MT_INBOX.getValue().equals(message.getType())) {
                        try {
                            messageDatabaseService.updateReadStatusForKeyString(message.getKeyString());
                            Intent intent = new Intent(getActivity(), ConversationReadService.class);
                            intent.putExtra(ConversationReadService.SINGLE_MESSAGE_READ, true);
                            intent.putExtra(ConversationReadService.CONTACT, contact);
                            intent.putExtra(ConversationReadService.CHANNEL, channel);
                            getActivity().startService(intent);
                        } catch (Exception e) {
                            Utils.printLog(getContext(), TAG, "Got exception while read");
                        }
                    }
                }

                selfDestructMessage(message);
            }
        });
    }

    protected abstract void processMobiTexterUserCheck();

    @Override
    public void onCreateContextMenu(ContextMenu menu, View view,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        if (view.getId() == R.id.messageList) {
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        this.menu = menu;

        if (contact != null && contact.isDeleted()) {
            menu.findItem(R.id.dial).setVisible(false);
            menu.findItem(R.id.refresh).setVisible(false);
            menu.removeItem(R.id.conversations);
            menu.findItem(R.id.userBlock).setVisible(false);
            menu.findItem(R.id.userUnBlock).setVisible(false);
            menu.findItem(R.id.dial).setVisible(false);
            return;
        }

        String contactNumber = contact != null ? contact.getContactNumber() : null;
        ApplozicClient setting = ApplozicClient.getInstance(getActivity());

        if ((setting.isHandleDial() && !TextUtils.isEmpty(contactNumber) && contactNumber.length() > 2)
                || (setting.isIPCallEnabled())) {
            if (setting.isIPCallEnabled()) {
                menu.findItem(R.id.dial).setVisible(true);
                menu.findItem(R.id.video_call).setVisible(true);
            }
            if (setting.isHandleDial()) {
                menu.findItem(R.id.dial).setVisible(true);
            }
        } else {
            menu.findItem(R.id.video_call).setVisible(false);
            menu.findItem(R.id.dial).setVisible(false);
        }
        if (channel != null) {
            menu.findItem(R.id.dial).setVisible(false);
            menu.findItem(R.id.video_call).setVisible(false);

            if (Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType())) {
                String userId = ChannelService.getInstance(getActivity()).getGroupOfTwoReceiverUserId(channel.getKey());
                if (!TextUtils.isEmpty(userId) && alCustomizationSettings.isBlockOption()) {
                    Contact withUserContact = appContactService.getContactById(userId);
                    if (withUserContact.isBlocked()) {
                        menu.findItem(R.id.userUnBlock).setVisible(true);
                    } else {
                        menu.findItem(R.id.userBlock).setVisible(true);
                    }
                }
            } else {
                menu.findItem(R.id.userBlock).setVisible(false);
                menu.findItem(R.id.userUnBlock).setVisible(false);
                if (alCustomizationSettings.isMuteOption()) {
                    menu.findItem(R.id.unmuteGroup).setVisible(!channel.isDeleted() && channel.isNotificationMuted());
                    menu.findItem(R.id.muteGroup).setVisible(!channel.isDeleted() && !channel.isNotificationMuted());
                }
            }
        } else if (contact != null && alCustomizationSettings.isBlockOption()) {
            if (contact.isBlocked()) {
                menu.findItem(R.id.userUnBlock).setVisible(true);
            } else {
                menu.findItem(R.id.userBlock).setVisible(true);
            }
        }

        menu.removeItem(R.id.menu_search);
        menu.removeItem(R.id.start_new);

        if (channel != null && channel.isDeleted()) {
            menu.findItem(R.id.refresh).setVisible(false);
            menu.findItem(R.id.deleteConversation).setVisible(false);
        } else {
            menu.findItem(R.id.refresh).setVisible(alCustomizationSettings.isRefreshOption());
            menu.findItem(R.id.deleteConversation).setVisible(alCustomizationSettings.isDeleteOption());
        }

        menu.removeItem(R.id.conversations);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.userBlock) {
            if (channel != null) {
                if (Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType())) {
                    String userId = ChannelService.getInstance(getActivity()).getGroupOfTwoReceiverUserId(channel.getKey());
                    if (!TextUtils.isEmpty(userId)) {
                        userBlockDialog(true, appContactService.getContactById(userId), true);
                    }
                }
            } else if (contact != null) {
                userBlockDialog(true, contact, false);
            }
        }
        if (id == R.id.userUnBlock) {
            if (channel != null) {
                if (Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType())) {
                    String userId = ChannelService.getInstance(getActivity()).getGroupOfTwoReceiverUserId(channel.getKey());
                    if (!TextUtils.isEmpty(userId)) {
                        userBlockDialog(false, appContactService.getContactById(userId), true);
                    }
                }
            } else if (contact != null) {
                userBlockDialog(false, contact, false);
            }
        }
        if (id == R.id.dial) {
            if (contact != null) {
                if (contact.isBlocked()) {
                    userBlockDialog(false, contact, false);
                } else {
                    ((ConversationActivity) getActivity()).processCall(contact, currentConversationId);
                }
            }
        }
        if (id == R.id.deleteConversation) {
            deleteConversationThread();
            return true;
        }

        if (id == R.id.video_call) {
            if (contact != null) {
                if (contact.isBlocked()) {
                    userBlockDialog(false, contact, false);
                } else {
                    ((ConversationActivity) getActivity()).processVideoCall(contact, currentConversationId);
                }
            }
        }
        if (id == R.id.muteGroup) {
            muteGroupChat();
        }
        if (id == R.id.unmuteGroup) {
            umuteGroupChat();
        }
        return false;
    }

    public void loadConversation(final Contact contact, final Channel channel, final Integer conversationId, final String searchString) {
        if (downloadConversation != null) {
            downloadConversation.cancel(true);
        }

        BroadcastService.currentUserId = contact != null ? contact.getContactIds() : String.valueOf(channel.getKey());
        typingStarted = false;
        onSelected = false;

        if (contact != null && contact.isDeleted()) {

        } else {
            individualMessageSendLayout.setVisibility(VISIBLE);
        }

        if (contact != null && this.channel != null) {
            if (menu != null) {
                menu.findItem(R.id.unmuteGroup).setVisible(false);
                menu.findItem(R.id.muteGroup).setVisible(false);
            }
        }
        /*
        filePath = null;*/
        if (TextUtils.isEmpty(filePath) && attachmentLayout != null) {
            attachmentLayout.setVisibility(GONE);
        }

        if (!TextUtils.isEmpty(defaultText) && myMessageEditText != null) {
            myMessageEditText.setText(defaultText);
            defaultText = "";
        }

        setContact(contact);
        setChannel(channel);

        unregisterForContextMenu(listView);
        clearList();
        updateTitle();
        swipeLayout.setEnabled(true);
        loadMore = true;
        if (selfDestructMessageSpinner != null) {
            selfDestructMessageSpinner.setSelection(0);
        }

        if (contact != null) {
            conversationAdapter = new DetailedConversationAdapter(getActivity(),
                    R.layout.mobicom_message_row_view, messageList, contact, messageIntentClass, emojiIconHandler);
            conversationAdapter.setAlCustomizationSettings(alCustomizationSettings);
        } else if (channel != null) {
            conversationAdapter = new DetailedConversationAdapter(getActivity(),
                    R.layout.mobicom_message_row_view, messageList, channel, messageIntentClass, emojiIconHandler);
            conversationAdapter.setAlCustomizationSettings(alCustomizationSettings);
        }
        listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
        listView.setAdapter(conversationAdapter);
        registerForContextMenu(listView);

        processMobiTexterUserCheck();

        if (contact != null) {
            if (!TextUtils.isEmpty(contact.getContactIds())) {
                NotificationManager notificationManager =
                        (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.cancel(contact.getContactIds().hashCode());
            }
        }

        if (channel != null) {
            NotificationManager notificationManager =
                    (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.cancel(String.valueOf(channel.getKey()).hashCode());
        }

        downloadConversation = new DownloadConversation(listView, true, 1, 0, 0, contact, channel, conversationId);
        AsyncTaskCompat.executeParallel(downloadConversation);


        emoticonsFrameLayout.setVisibility(GONE);

        if (contact != null) {
            Intent intent = new Intent(getActivity(), UserIntentService.class);
            intent.putExtra(UserIntentService.USER_ID, contact.getUserId());
            getActivity().startService(intent);

        }

        if (channel != null) {
            if (Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType())) {
                String userId = ChannelService.getInstance(getActivity()).getGroupOfTwoReceiverUserId(channel.getKey());
                if (!TextUtils.isEmpty(userId)) {
                    Intent intent = new Intent(getActivity(), UserIntentService.class);
                    intent.putExtra(UserIntentService.USER_ID, userId);
                    getActivity().startService(intent);
                }
            } else {
                updateChannelSubTitle();
            }
        }

        InstructionUtil.showInstruction(getActivity(), R.string.instruction_go_back_to_recent_conversation_list, MobiComKitActivityInterface.INSTRUCTION_DELAY, BroadcastService.INTENT_ACTIONS.INSTRUCTION.toString());
    }


    public void updateLastSeenStatus() {
        if (this.getActivity() == null) {
            return;
        }
        if (contact != null) {
            contact = appContactService.getContactById(contact.getContactIds());
        }

        if (contact != null) {
            processUpdateLastSeenStatus(contact);
        } else if (channel != null && Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType())) {
            String userId = ChannelService.getInstance(getActivity()).getGroupOfTwoReceiverUserId(channel.getKey());
            if (!TextUtils.isEmpty(userId)) {
                Contact withUserContact = appContactService.getContactById(userId);
                processUpdateLastSeenStatus(withUserContact);
            }

        }

    }


    protected void processUpdateLastSeenStatus(final Contact withUserContact) {
        if (withUserContact == null) {
            return;
        }

        if (individualMessageSendLayout != null) {
            individualMessageSendLayout.setVisibility(withUserContact.isDeleted() ? GONE : VISIBLE);
        }

        if (menu != null) {
            menu.findItem(R.id.userBlock).setVisible(alCustomizationSettings.isBlockOption() ? !withUserContact.isDeleted() && !withUserContact.isBlocked() : alCustomizationSettings.isBlockOption());
            menu.findItem(R.id.userUnBlock).setVisible(alCustomizationSettings.isBlockOption() ? !withUserContact.isDeleted() && withUserContact.isBlocked() : alCustomizationSettings.isBlockOption());
            menu.findItem(R.id.refresh).setVisible(alCustomizationSettings.isRefreshOption() ? !withUserContact.isDeleted() : alCustomizationSettings.isRefreshOption());

        }

        if (withUserContact.isBlocked() || withUserContact.isBlockedBy() || withUserContact.isDeleted()) {
            return;
        }
    }

    public void updateChannelSubTitle() {
        channelUserMapperList = ChannelService.getInstance(getActivity()).getListOfUsersFromChannelUserMapper(channel.getKey());
        if (channelUserMapperList != null && channelUserMapperList.size() > 0) {
            if (Channel.GroupType.GROUPOFTWO.getValue() != null && Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType())) {
                String userId = ChannelService.getInstance(getActivity()).getGroupOfTwoReceiverUserId(channel.getKey());
                if (!TextUtils.isEmpty(userId)) {
                    Contact withUserContact = appContactService.getContactById(userId);
                }

            } else {
                StringBuffer stringBuffer = new StringBuffer();
                Contact contactDisplayName;
                String youString = null;
                int i = 0;
                for (ChannelUserMapper channelUserMapper : channelUserMapperList) {
                    i++;
                    if (i > 20)
                        break;
                    contactDisplayName = appContactService.getContactById(channelUserMapper.getUserKey());
                    if (!TextUtils.isEmpty(channelUserMapper.getUserKey())) {
                        if (MobiComUserPreference.getInstance(getActivity()).getUserId() != null && MobiComUserPreference.getInstance(getActivity()).getUserId().equals(channelUserMapper.getUserKey())) {
                            youString = "";
                        } else {
                            stringBuffer.append(contactDisplayName.getDisplayName()).append(",");
                        }
                    }
                }

            }

        }
    }

    public boolean isBroadcastedToChannel(Integer channelKey) {
        return getChannel() != null && getChannel().getKey().equals(channelKey);
    }

    public boolean getCurrentChannelKey(Integer channelKey) {
        return channel != null && channel.getKey().equals(channelKey);
    }

    public Channel getChannel() {
        return channel;
    }

    protected void setChannel(Channel channel) {
        this.channel = channel;
    }

    public boolean isMsgForConversation(Message message) {

        if (BroadcastService.isContextBasedChatEnabled() && message.getConversationId() != null) {
            return isMessageForCurrentConversation(message) && compareConversationId(message);
        }
        return isMessageForCurrentConversation(message);
    }

    public boolean isMessageForCurrentConversation(Message message) {
        return (message.getGroupId() != null && channel != null && message.getGroupId().equals(channel.getKey())) ||
                (!TextUtils.isEmpty(message.getContactIds()) && contact != null && message.getContactIds().equals(contact.getContactIds())) && message.getGroupId() == null;
    }

    public boolean compareConversationId(Message message) {
        return message.getConversationId() != null && currentConversationId != null && message.getConversationId().equals(currentConversationId);
    }

    public void updateUploadFailedStatus(Message message) {
        int i = messageList.indexOf(message);
        if (i != -1) {
            messageList.get(i).setCanceled(true);
            conversationAdapter.notifyDataSetChanged();
        }

    }

    public void downloadFailed(final Message message) {
        this.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                int index = messageList.indexOf(message);
                if (index != -1) {
                    View view = listView.getChildAt(index -
                            listView.getFirstVisiblePosition() + 1);

                    if (view != null) {
                        final LinearLayout attachmentDownloadLayout = view.findViewById(R.id.attachment_download_layout);
                        attachmentDownloadLayout.setVisibility(VISIBLE);
                    }

                }
            }

        });
    }

    abstract public void attachLocation(Location mCurrentLocation);

    public void updateDeliveryStatusForAllMessages(final boolean markRead) {

        this.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    Drawable statusIcon = getResources().getDrawable(R.drawable.applozic_ic_action_message_delivered);
                    if (markRead) {
                        statusIcon = getResources().getDrawable(R.drawable.applozic_ic_action_message_read);
                    }
                    for (int index = 0; index < messageList.size(); index++) {
                        Message message = messageList.get(index);
                        if ((message.getStatus() == Message.Status.DELIVERED_AND_READ.getValue()) || message.isTempDateType() || message.isCustom() || !message.isTypeOutbox() || message.isChannelCustomMessage()) {
                            continue;
                        }
                        if (messageList.get(index) != null) {
                            messageList.get(index).setDelivered(true);
                        }
                        message.setDelivered(true);
                        if (markRead) {
                            if (messageList.get(index) != null) {
                                messageList.get(index).setStatus(Message.Status.DELIVERED_AND_READ.getValue());
                            }
                            message.setStatus(Message.Status.DELIVERED_AND_READ.getValue());
                        }
                        View view = listView.getChildAt(index -
                                listView.getFirstVisiblePosition() + 1);
                        if (view != null && !message.isCustom() && !message.isChannelCustomMessage()) {
//                            TextView createdAtTime = (TextView) view.findViewById(R.id.createdAtTime);
                            TextView status = view.findViewById(R.id.status);
                            //status.setText("Delivered");
//                            createdAtTime.setCompoundDrawablesWithIntrinsicBounds(null, null, statusIcon, null);
                        }
                    }
                } catch (Exception ex) {
                    Utils.printLog(getContext(), TAG, "Exception while updating delivery status in UI.");
                }
            }
        });
    }

    public void updateDeliveryStatus(final Message message) {
        this.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    int index = messageList.indexOf(message);
                    if (index != -1) {
                        if (messageList.get(index).getStatus() == Message.Status.DELIVERED_AND_READ.getValue()
                                || messageList.get(index).isTempDateType()
                                || messageList.get(index).isCustom()
                                || messageList.get(index).isChannelCustomMessage()) {
                            return;
                        }
                        messageList.get(index).setDelivered(true);
                        messageList.get(index).setStatus(message.getStatus());
                        View view = listView.getChildAt(index -
                                listView.getFirstVisiblePosition() + 1);
                        if (view != null && !messageList.get(index).isCustom()) {
                            Drawable statusIcon = getResources().getDrawable(R.drawable.applozic_ic_action_message_delivered);
                            if (message.getStatus() == Message.Status.DELIVERED_AND_READ.getValue()) {
                                statusIcon = getResources().getDrawable(R.drawable.applozic_ic_action_message_read);
                                messageList.get(index).setStatus(Message.Status.DELIVERED_AND_READ.getValue());
                            }
                        }
                    } else if (!message.isVideoNotificationMessage() && !message.isHidden()) {
                        messageList.add(message);
                        listView.smoothScrollToPosition(messageList.size());
                        listView.setSelection(messageList.size());
                        emptyTextView.setVisibility(GONE);
                        conversationAdapter.notifyDataSetChanged();
                    }
                } catch (Exception ex) {
                    Utils.printLog(getContext(), TAG, "Exception while updating delivery status in UI.");
                }
            }
        });
    }

    public void loadFile(Uri uri) {
        loadFile(uri, null);
    }

    public void loadFile(Uri uri, File file) {
        if (uri == null || file == null) {
            Toast.makeText(getActivity(), R.string.file_not_selected, Toast.LENGTH_LONG).show();
            return;
        }
        handleSendAndRecordButtonView(true);
        filePath = Uri.parse(file.getAbsolutePath()).toString();
        if (TextUtils.isEmpty(filePath)) {
            Utils.printLog(getContext(), TAG, "Error while fetching filePath");
            attachmentLayout.setVisibility(GONE);
            Toast.makeText(getActivity(), R.string.info_file_attachment_error, Toast.LENGTH_LONG).show();
            return;
        }
        String mimeType = getActivity().getContentResolver().getType(uri);
        Cursor returnCursor =
                getActivity().getContentResolver().query(uri, null, null, null, null);
        if (returnCursor != null) {
            int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
            returnCursor.moveToFirst();
            Long fileSize = returnCursor.getLong(sizeIndex);
            int maxFileSize = alCustomizationSettings.getMaxAttachmentSizeAllowed() * 1024 * 1024;
            if (fileSize > maxFileSize) {
                Toast.makeText(getActivity(), R.string.info_attachment_max_allowed_file_size, Toast.LENGTH_LONG).show();
                return;
            }
            attachedFile.setText(returnCursor.getString(returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)));
            returnCursor.close();
        }
        attachmentLayout.setVisibility(VISIBLE);
        if (mimeType != null && (mimeType.startsWith("image") || mimeType.startsWith("video"))) {
            attachedFile.setVisibility(GONE);
            int reqWidth = mediaContainer.getWidth();
            int reqHeight = mediaContainer.getHeight();
            if (reqWidth == 0 || reqHeight == 0) {
                DisplayMetrics displaymetrics = new DisplayMetrics();
                getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
                reqHeight = displaymetrics.heightPixels;
                reqWidth = displaymetrics.widthPixels;
            }
            previewThumbnail = FileUtils.getPreview(filePath, reqWidth, reqHeight, alCustomizationSettings.isImageCompression(), mimeType);
            mediaContainer.setImageBitmap(previewThumbnail);
        } else {
            attachedFile.setVisibility(VISIBLE);
            mediaContainer.setImageBitmap(null);
        }
    }

    public synchronized boolean updateMessageList(Message message, boolean update) {
        boolean toAdd = !messageList.contains(message);
        if (update) {
            messageList.remove(message);
            messageList.add(message);
        } else if (toAdd) {
            Message firstDateMessage = new Message();
            firstDateMessage.setTempDateType(Short.valueOf("100"));
            firstDateMessage.setCreatedAtTime(message.getCreatedAtTime());
            if (!messageList.contains(firstDateMessage)) {
                messageList.add(firstDateMessage);
            }

            messageList.add(message);
        }
        return toAdd;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        support = new Support(activity);
        try {
            messageCommunicator = (MessageCommunicator) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement interfaceDataCommunicator");
        }
    }


    public String getNameForInviteDialog() {
        if (contact != null) {
            return contact.getDisplayName();
        } else if (channel != null) {
            if (Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType())) {
                String userId = ChannelService.getInstance(getActivity()).getGroupOfTwoReceiverUserId(channel.getKey());
                if (!TextUtils.isEmpty(userId)) {
                    Contact withUserContact = appContactService.getContactById(userId);
                    return withUserContact.getDisplayName();
                }
            } else {
                return ChannelUtils.getChannelTitleName(channel, MobiComUserPreference.getInstance(getActivity()).getUserId());
            }
        }
        return "";
    }

    public void onClickOnMessageReply(Message message) {
        if (message != null) {
            if (listView != null) {
                int height = listView.getHeight();
                int itemHeight = listView.getChildAt(0).getHeight();
                int index = messageList.indexOf(message);
                if (index != -1) {
                    listView.requestFocusFromTouch();
                    listView.setSelectionFromTop(index + 1, height / 2 - itemHeight / 2);
                    listView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (listView != null) {
                                try {
                                    if (listView.isFocused()) {
                                        listView.clearFocus();
                                    }
                                } catch (Exception e) {
                                }
                            }
                        }
                    }, 800);
                }
            }

        }
    }

    public void forwardMessage(Message messageToForward, Contact contact, Channel channel) {
        this.contact = contact;
        this.channel = channel;
        if (messageToForward.isAttachmentDownloaded() && messageToForward.getFilePaths().size() > 0) {
            filePath = messageToForward.getFilePaths().get(0);
        }
        this.messageToForward = messageToForward;
        loadConversation(contact, channel, currentConversationId, null);

    }

    private void sendForwardMessage(Message messageToForward) {
        //reset Messages Fields...
        MobiComUserPreference userPreferences = MobiComUserPreference.getInstance(getActivity());

        if (channel != null) {
            if (!ChannelService.getInstance(getContext()).processIsUserPresentInChannel(channel.getKey())) {
                return;
            }
            messageToForward.setGroupId(channel.getKey());
            messageToForward.setClientGroupId(null);
            messageToForward.setContactIds(null);
            messageToForward.setTo(null);
        } else {
            if (contact.isBlocked()) {
                return;
            }
            messageToForward.setGroupId(null);
            messageToForward.setClientGroupId(null);
            messageToForward.setTo(contact.getContactIds());
            messageToForward.setContactIds(contact.getContactIds());
        }

        messageToForward.setKeyString(null);
        messageToForward.setMessageId(null);
        messageToForward.setDelivered(false);
        messageToForward.setRead(Boolean.TRUE);
        messageToForward.setStoreOnDevice(Boolean.TRUE);
        messageToForward.setCreatedAtTime(System.currentTimeMillis() + userPreferences.getDeviceTimeOffset());
        if (currentConversationId != null && currentConversationId != 0) {
            messageToForward.setConversationId(currentConversationId);
        }
        Map<String, String> metaDataMapForward = messageToForward.getMetadata();
        if (metaDataMapForward != null && !metaDataMapForward.isEmpty() && metaDataMapForward.get(Message.MetaDataType.AL_REPLY.getValue()) != null) {
            messageToForward.setMetadata(null);
        }
        messageToForward.setSendToDevice(Boolean.FALSE);
        messageToForward.setType(Message.MessageType.MT_OUTBOX.getValue());
        messageToForward.setTimeToLive(getTimeToLive());
        messageToForward.setSentToServer(false);
        messageToForward.setStatus(Message.Status.READ.getValue());

        if (!TextUtils.isEmpty(filePath)) {
            List<String> filePaths = new ArrayList<>();
            filePaths.add(filePath);
            messageToForward.setFilePaths(filePaths);
        }
        conversationService.sendMessage(messageToForward, messageIntentClass);
        if (selfDestructMessageSpinner != null) {
            selfDestructMessageSpinner.setSelection(0);
        }
        attachmentLayout.setVisibility(GONE);
        filePath = null;
    }

    /**
     * 发送消息
     *
     * @param message
     * @param messageMetaData
     * @param fileMetas
     * @param fileMetaKeyStrings
     * @param messageContentType
     */
    public void sendMessage(String message, Map<String, String> messageMetaData, FileMeta fileMetas, String fileMetaKeyStrings, short messageContentType) {
        if (messageMetaData == null) {
            messageMetaData = new HashMap<>();
        }
        MobiComUserPreference userPreferences = MobiComUserPreference.getInstance(getActivity());
        Message messageToSend = new Message();

        if (channel != null) {
            messageToSend.setGroupId(channel.getKey());
            if (!TextUtils.isEmpty(channel.getClientGroupId())) {
                messageToSend.setClientGroupId(channel.getClientGroupId());
            }
        } else {
            messageToSend.setTo(contact.getContactIds());
            messageToSend.setContactIds(contact.getContactIds());
        }
        messageToSend.setRead(Boolean.TRUE);
        messageToSend.setStoreOnDevice(Boolean.TRUE);
        if (messageToSend.getCreatedAtTime() == null) {
            messageToSend.setCreatedAtTime(System.currentTimeMillis() + userPreferences.getDeviceTimeOffset());
        }
        if (currentConversationId != null && currentConversationId != 0) {
            messageToSend.setConversationId(currentConversationId);
        }
        messageToSend.setSendToDevice(Boolean.FALSE);
        messageToSend.setType(Message.MessageType.MT_OUTBOX.getValue());
        messageToSend.setTimeToLive(getTimeToLive());
        messageToSend.setMessage(message);
        messageToSend.setDeviceKeyString(userPreferences.getDeviceKeyString());
        messageToSend.setScheduledAt(scheduledTimeHolder.getTimestamp());
        messageToSend.setSource(Message.Source.MT_MOBILE_APP.getValue());
        if (!TextUtils.isEmpty(filePath)) {
            List<String> filePaths = new ArrayList<>();
            filePaths.add(filePath);
            messageToSend.setFilePaths(filePaths);
            if (messageContentType == Message.ContentType.AUDIO_MSG.getValue() || messageContentType == Message.ContentType.CONTACT_MSG.getValue() || messageContentType == Message.ContentType.VIDEO_MSG.getValue()) {
                messageToSend.setContentType(messageContentType);
            } else {
                messageToSend.setContentType(Message.ContentType.ATTACHMENT.getValue());
            }
        } else {
            messageToSend.setContentType(messageContentType);
        }
        messageToSend.setFileMetaKeyStrings(fileMetaKeyStrings);
        messageToSend.setFileMetas(fileMetas);
        if (!TextUtils.isEmpty(ApplozicClient.getInstance(getActivity()).getMessageMetaData())) {
            Type mapType = new TypeToken<Map<String, String>>() {
            }.getType();
            Map<String, String> messageMetaDataMap;
            try {
                messageMetaDataMap = new Gson().fromJson(ApplozicClient.getInstance(getActivity()).getMessageMetaData(), mapType);
                if (messageMetaDataMap != null) {
                    messageMetaData.putAll(messageMetaDataMap);
                }
                messageToSend.setMetadata(messageMetaData);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if (messageContentType == Message.ContentType.AUDIO_MSG.getValue()) {
                int time = (int) (voiceDuration / 1000);
                messageMetaData.put(ChatConfig.VOICE_DURATION, time + "");
                messageToSend.setMetadata(messageMetaData);
            } else {
                messageToSend.setMetadata(messageMetaData);
            }
        }

        if (messageContentType == Message.ContentType.RED_PACKET.getValue()) {
            messageToSend.setMetadata(messageMetaData);
            messageToSend.setMessage("我正在发红包，快来抢");
        } else if (messageContentType == Message.ContentType.RED_PACKET_RESPONSE.getValue()) {
            messageToSend.setMessage("我正在抢红包，快来哦");
            messageToSend.setMetadata(messageMetaData);
        } else if (messageContentType == Message.ContentType.GIVE_PRIZE.getValue()) {
            messageToSend.setMetadata(messageMetaData);
            messageToSend.setMessage("打赏消息");
        }
        conversationService.sendMessage(messageToSend, messageIntentClass);

        if (selfDestructMessageSpinner != null) {
            selfDestructMessageSpinner.setSelection(0);
        }
        attachmentLayout.setVisibility(GONE);
        if (channel != null && channel.getType() != null && Channel.GroupType.BROADCAST_ONE_BY_ONE.getValue().equals(channel.getType())) {
            sendBroadcastMessage(message, filePath);
        }
        filePath = null;
    }

    public void sendProductMessage(final String messageToSend, final FileMeta fileMeta, final Contact contact, final short messageContentType) {
        final Message message = new Message();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String topicId;
                MobiComConversationService conversationService = new MobiComConversationService(getActivity());
                MobiComUserPreference userPreferences = MobiComUserPreference.getInstance(getActivity());
                topicId = new MessageClientService(getActivity()).getTopicId(currentConversationId);
                if (getChannel() != null) {
                    message.setGroupId(channelKey);
                } else {
                    message.setContactIds(contact.getUserId());
                    message.setTo(contact.getUserId());
                }
                message.setMessage(messageToSend);
                message.setRead(Boolean.TRUE);
                message.setStoreOnDevice(Boolean.TRUE);
                message.setSendToDevice(Boolean.FALSE);
                message.setContentType(messageContentType);
                message.setType(Message.MessageType.MT_OUTBOX.getValue());
                message.setDeviceKeyString(userPreferences.getDeviceKeyString());
                message.setSource(Message.Source.MT_MOBILE_APP.getValue());
                message.setTopicId(messageToSend);
                message.setCreatedAtTime(System.currentTimeMillis() + userPreferences.getDeviceTimeOffset());
                message.setTopicId(topicId);
                message.setConversationId(currentConversationId);
                message.setFileMetas(fileMeta);
                conversationService.sendMessage(message, MessageIntentService.class);
            }
        }).start();

    }

    public void sendBroadcastMessage(String message, String path) {
        MobiComUserPreference userPreferences = MobiComUserPreference.getInstance(getActivity());
        if (channelUserMapperList != null && channelUserMapperList.size() > 0) {
            for (ChannelUserMapper channelUserMapper : channelUserMapperList) {
                if (!userPreferences.getUserId().equals(channelUserMapper.getUserKey())) {
                    Message messageToSend = new Message();
                    messageToSend.setTo(channelUserMapper.getUserKey());
                    messageToSend.setContactIds(channelUserMapper.getUserKey());
                    messageToSend.setRead(Boolean.TRUE);
                    messageToSend.setStoreOnDevice(Boolean.TRUE);
                    if (messageToSend.getCreatedAtTime() == null) {
                        messageToSend.setCreatedAtTime(System.currentTimeMillis() + userPreferences.getDeviceTimeOffset());
                    }
                    if (currentConversationId != null && currentConversationId != 0) {
                        messageToSend.setConversationId(currentConversationId);
                    }
                    messageToSend.setSendToDevice(Boolean.FALSE);
                    messageToSend.setType(Message.MessageType.MT_OUTBOX.getValue());
                    messageToSend.setTimeToLive(getTimeToLive());
                    messageToSend.setMessage(message);
                    messageToSend.setDeviceKeyString(userPreferences.getDeviceKeyString());
                    messageToSend.setScheduledAt(scheduledTimeHolder.getTimestamp());
                    messageToSend.setSource(Message.Source.MT_MOBILE_APP.getValue());
                    if (!TextUtils.isEmpty(path)) {
                        List<String> filePaths = new ArrayList<>();
                        filePaths.add(path);
                        messageToSend.setFilePaths(filePaths);
                    }
                    conversationService.sendMessage(messageToSend, MessageIntentService.class);

                    if (selfDestructMessageSpinner != null) {
                        selfDestructMessageSpinner.setSelection(0);
                    }
                    attachmentLayout.setVisibility(GONE);
                }
            }
        }
    }

    private Integer getTimeToLive() {
        if (selfDestructMessageSpinner == null || selfDestructMessageSpinner.getSelectedItemPosition() <= 1) {
            return null;
        }
        return Integer.parseInt(selfDestructMessageSpinner.getSelectedItem().toString().replace("mins", "").replace("min", "").trim());
    }

    public void sendMessage(String message, Map<String, String> messageMetaData) {
        sendMessage(message, messageMetaData, null, null, Message.ContentType.DEFAULT.getValue());
    }

    public void sendMessage(short messageContentType, String filePath, Map<String, String> messageMetaData) {
        this.filePath = filePath;
        sendMessage("", messageContentType, messageMetaData);
    }

    public void sendMessage(Short value, String selectedFilePath, long voiceDuration, Map<String, String> messageMetaData) {
        this.voiceDuration = voiceDuration;
        sendMessage(value, selectedFilePath, messageMetaData);
    }

    public void sendMessage(String message, short messageContentType, String filePath, Map<String, String> messageMetaData) {
        this.filePath = filePath;
        sendMessage(message, messageMetaData, null, null, messageContentType);
    }

    public void sendMessage(String message, short messageContentType, Map<String, String> messageMetaData) {
        sendMessage(message, messageMetaData, null, null, messageContentType);
    }

    public void sendMessage(String message, Map<String, String> messageMetaData, short messageContentType) {
        sendMessage(message, messageMetaData, null, null, messageContentType);
    }

    public void updateMessageKeyString(final Message message) {
        this.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                int index = messageList.indexOf(message);
                if (index != -1) {
                    Message messageListItem = messageList.get(index);
                    messageListItem.setKeyString(message.getKeyString());
                    messageListItem.setSentToServer(true);
                    messageListItem.setCreatedAtTime(message.getSentMessageTimeAtServer());
                    messageListItem.setFileMetaKeyStrings(message.getFileMetaKeyStrings());
                    messageListItem.setFileMetas(message.getFileMetas());
                    if (messageList.get(index) != null) {
                        messageList.get(index).setKeyString(message.getKeyString());
                        messageList.get(index).setSentToServer(true);
                        messageList.get(index).setCreatedAtTime(message.getSentMessageTimeAtServer());
                        messageList.get(index).setFileMetaKeyStrings(message.getFileMetaKeyStrings());
                        messageList.get(index).setFileMetas(message.getFileMetas());
                    }
                    View view = listView.getChildAt(index - listView.getFirstVisiblePosition() + 1);
                    if (view != null) {
                        ProgressBar mediaUploadProgressBarIndividualMessage = view.findViewById(R.id.media_upload_progress_bar);
                        RelativeLayout downloadInProgressLayout = view.findViewById(R.id.applozic_doc_download_progress_rl);
                        if (mediaUploadProgressBarIndividualMessage != null) {
                            mediaUploadProgressBarIndividualMessage.setVisibility(GONE);
                        }
                        if (downloadInProgressLayout != null) {
                            downloadInProgressLayout.setVisibility(GONE);
                        }
                        if (message.getFileMetas() != null && !"image".contains(message.getFileMetas().getContentType()) && !"video".contains(message.getFileMetas().getContentType())) {
                            RelativeLayout applozicDocRelativeLayout = view.findViewById(R.id.applozic_doc_downloaded);
                            ImageView imageViewDoc = applozicDocRelativeLayout.findViewById(R.id.doc_icon);
                            if (message.getFileMetas() != null) {
                                if (message.getFileMetas().getContentType().contains("audio")) {
                                    imageViewDoc.setImageResource(R.drawable.ic_play_circle_outline);
                                } else {
                                }
                                applozicDocRelativeLayout.setVisibility(VISIBLE);
                            } else if (message.getFilePaths() != null && message.getFilePaths().size() > 0) {
                                String filePath = message.getFilePaths().get(0);
                                final String mimeType = FileUtils.getMimeType(filePath);
                                if (mimeType.contains("audio")) {
                                    imageViewDoc.setImageResource(R.drawable.ic_play_circle_outline);
                                } else {
                                }
                                applozicDocRelativeLayout.setVisibility(VISIBLE);
                            }
                        }
                    }
                }
            }
        });
    }

    public void updateDownloadStatus(final Message message) {
        this.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    int index = messageList.indexOf(message);
                    if (index != -1) {
                        Message smListItem = messageList.get(index);
                        smListItem.setKeyString(message.getKeyString());
                        smListItem.setFileMetaKeyStrings(message.getFileMetaKeyStrings());
                        if (messageList.get(index) != null) {
                            messageList.get(index).setKeyString(message.getKeyString());
                            messageList.get(index).setFileMetaKeyStrings(message.getFileMetaKeyStrings());
                        }
                        View view = listView.getChildAt(index - listView.getFirstVisiblePosition() + 1);
                        if (view != null) {
                            if (applozicDocumentView != null) {
                                applozicDocumentView.inflateViewWithMessage(view, message);
                            }
                            final RelativeLayout attachmentDownloadProgressLayout = view.findViewById(R.id.attachment_download_progress_layout);
                            final AttachmentView attachmentView = view.findViewById(R.id.main_attachment_view);
                            final ImageView preview = view.findViewById(R.id.preview);
                            TextView audioDurationTextView = view.findViewById(R.id.audio_duration_textView);
                            final ImageView videoIcon = view.findViewById(R.id.video_icon);
                            String audioDuration;
                            if (message.getFileMetas() != null && message.getFileMetas().getContentType().contains("image")) {
                                attachmentView.setVisibility(VISIBLE);
                                preview.setVisibility(GONE);
                                attachmentView.setMessage(smListItem);
                                attachmentDownloadProgressLayout.setVisibility(GONE);
                            } else if (message.getFileMetas() != null && message.getFileMetas().getContentType().contains("video")) {
                                FileClientService fileClientService = new FileClientService(getContext());
                                attachedFile.setVisibility(GONE);
                                preview.setVisibility(VISIBLE);
                                videoIcon.setVisibility(VISIBLE);
                                preview.setImageBitmap(fileClientService.createAndSaveVideoThumbnail(message.getFilePaths().get(0)));
                            } else if (message.getFileMetas() != null) {
                                //Hide Attachment View...
                                RelativeLayout applozicDocRelativeLayout = view.findViewById(R.id.applozic_doc_downloaded);
                                ImageView imageViewDoc = applozicDocRelativeLayout.findViewById(R.id.doc_icon);
                                if (message.getFileMetas() != null && message.getFilePaths() == null) {
                                    if (message.getFileMetas().getContentType().contains("audio")) {
                                        imageViewDoc.setImageResource(R.drawable.ic_play_circle_outline);
                                    } else {
//                                        imageViewDoc.setImageResource(R.drawable.ic_documentreceive);
                                    }
                                    applozicDocRelativeLayout.setVisibility(VISIBLE);
                                } else if (message.getFilePaths() != null) {
                                    String filePath = message.getFilePaths().get(0);
                                    final String mimeType = FileUtils.getMimeType(filePath);
                                    if (mimeType.contains("audio")) {
                                        if (message.isAttachmentDownloaded()) {
                                            audioDuration = ApplozicAudioManager.getInstance(getContext()).refreshAudioDuration(filePath);
                                            audioDurationTextView.setVisibility(View.VISIBLE);
                                            audioDurationTextView.setText(audioDuration);
                                        } else {
                                            audioDurationTextView.setVisibility(View.VISIBLE);
                                            audioDurationTextView.setText("00:00");
                                        }
                                        imageViewDoc.setImageResource(R.drawable.ic_play_circle_outline);
                                    } else {
//                                        imageViewDoc.setImageResource(R.drawable.ic_documentreceive);
                                    }
                                    applozicDocRelativeLayout.setVisibility(VISIBLE);
                                }
                                view.findViewById(R.id.applozic_doc_download_progress_rl).setVisibility(GONE);
                                //直接播放语音
                                if (message.getFilePaths() != null) {
                                    if (applozicDocumentView != null) {
//                                        applozicDocumentView.setMessage(message);
                                        applozicDocumentView.playSound();
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    Utils.printLog(getContext(), TAG, "Exception while updating download status: " + ex.getMessage());
                }
            }
        });
    }

    public void setDefaultText(String defaultText) {
        this.defaultText = defaultText;
    }

    public void setConversationId(Integer conversationId) {
        this.currentConversationId = conversationId;
    }

    public void updateUserTypingStatus(final String typingUserId, final String isTypingStatus) {
        if (contact != null) {
            if (contact.isBlocked() || contact.isBlockedBy()) {
                return;
            }
        }
        this.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isTypingStatus.equals("1")) {
                    if (channel != null) {
                        if (!MobiComUserPreference.getInstance(getActivity()).getUserId().equals(typingUserId)) {
                            Contact displayNameContact = appContactService.getContactById(typingUserId);
                            if (displayNameContact.isBlocked() || displayNameContact.isBlockedBy()) {
                                return;
                            }

                        }
                    }
                } else {
                    if (channel != null) {
                        if (!MobiComUserPreference.getInstance(getActivity()).getUserId().equals(typingUserId)) {
                            Contact displayNameContact = appContactService.getContactById(typingUserId);
                            if (displayNameContact.isBlocked() || displayNameContact.isBlockedBy()) {
                                return;
                            }
                            updateChannelSubTitle();
                        }
                    } else {
                        updateLastSeenStatus();
                    }

                }
            }
        });
    }

    //TODO: Please add onclick events here...  anonymous class are
    // TODO :hard to read and suggested if we have very few event view
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.emoji_button) {
            //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_chat_face_tap");

            if (emoticonsFrameLayout.getVisibility() == VISIBLE) {
                emoticonsFrameLayout.setVisibility(GONE);
                Utils.toggleSoftKeyBoard(getActivity(), false);
            } else {
                Utils.toggleSoftKeyBoard(getActivity(), true);
                emoticonsFrameLayout.setVisibility(VISIBLE);
                multimediaPopupGrid.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (longPress) {
            count = 0;
            longPress = false;
            applozicAudioRecordManager.cancelAudio();
            myMessageRecord.setText("按住说话");
            utils.Utils.muteAudioFocus(getContext(), false);
            record_tip.setVisibility(GONE);
            start_audio.setVisibility(GONE);
            mainEditTextLinearLayout.setBackgroundResource(R.drawable.bg_corners_chat);
            mainEditTextLinearLayout.setVisibility(VISIBLE);
        }
        BroadcastService.currentUserId = null;
        BroadcastService.currentConversationId = null;
        if (typingStarted) {
            Intent intent = new Intent(getActivity(), ApplozicMqttIntentService.class);
            intent.putExtra(ApplozicMqttIntentService.CHANNEL, channel);
            intent.putExtra(ApplozicMqttIntentService.CONTACT, contact);
            intent.putExtra(ApplozicMqttIntentService.TYPING, false);
            getActivity().startService(intent);
            typingStarted = false;
        }
        Intent intent = new Intent(getActivity(), ApplozicMqttIntentService.class);
        intent.putExtra(ApplozicMqttIntentService.CHANNEL, channel);
        intent.putExtra(ApplozicMqttIntentService.UN_SUBSCRIBE_TO_TYPING, true);
        getActivity().startService(intent);
        if (conversationAdapter != null) {
            conversationAdapter.contactImageLoader.setPauseWork(false);
        }
    }

    public void updateTitle() {
        StringBuilder stringBufferTitle = new StringBuilder();
        if (contact != null) {
            stringBufferTitle.append(contact.getDisplayName());
        } else if (channel != null) {
            if (Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType())) {
                String userId = ChannelService.getInstance(getActivity()).getGroupOfTwoReceiverUserId(channel.getKey());
                if (!TextUtils.isEmpty(userId)) {
                    Contact withUserContact = appContactService.getContactById(userId);
                    stringBufferTitle.append(withUserContact.getDisplayName());
                }
            } else {
                stringBufferTitle.append(ChannelUtils.getChannelTitleName(channel, MobiComUserPreference.getInstance(getActivity()).getUserId()));
            }
        }
        if (stringBufferTitle != null) {
            if (stringBufferTitle == null || stringBufferTitle.toString().equals("null")) {
                ((TextView) (getActivity()).findViewById(R.id.group_name)).setText("");
            } else {
                if (getActivity() == null) {
                    return;
                }
                TextView roomName = getActivity().findViewById(R.id.group_name);
                boolean isSingle = getActivity().getIntent().getBooleanExtra("is_single", false);
                if (!isSingle && roomCount != 0) {
                    roomName.setText(stringBufferTitle.toString() + "(" + roomCount + ")");
                } else {
                    roomName.setText(stringBufferTitle.toString());
                }
            }
        }

    }

    public void loadConversation(Channel channel, Integer conversationId) {
        loadConversation(null, channel, conversationId, null);
    }

    public void loadConversation(Contact contact, Integer conversationId) {
        loadConversation(contact, null, conversationId, null);
    }

    //With search
    public void loadConversation(Contact contact, Integer conversationId, String searchString) {
        loadConversation(contact, null, conversationId, searchString);
    }

    public void loadConversation(Channel channel, Integer conversationId, String searchString) {
        loadConversation(null, channel, conversationId, searchString);
    }

    public void deleteConversationThread() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity()).
                setPositiveButton(R.string.delete_conversation, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        new DeleteConversationAsyncTask(new MobiComConversationService(getActivity()), contact, channel, currentConversationId, getActivity()).execute();
                    }
                });
        alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            }
        });
        alertDialog.setTitle(getActivity().getString(R.string.dialog_delete_conversation_title).replace("[name]", getNameForInviteDialog()));
        alertDialog.setMessage(getActivity().getString(R.string.dialog_delete_conversation_confir).replace("[name]", getNameForInviteDialog()));
        alertDialog.setCancelable(true);
        alertDialog.create().show();
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int position = info.position - 1;
        if (messageList.size() <= position) {
            return true;
        }
        Message message = messageList.get(position);
        if (message.isTempDateType() || message.isCustom()) {
            return true;
        }

        switch (item.getItemId()) {
            case 0:
                android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                android.content.ClipData clip = android.content.ClipData.newPlainText(getContext().getString(R.string.copied_message), message.getMessage());
                clipboard.setPrimaryClip(clip);
                break;
            case 1:
                conversationUIService.startContactActivityForResult(message, null);
                break;
            case 2:
                Message messageToResend = new Message(message);
                //messageToResend.setCreatedAtTime(new Date().getTime());
                messageToResend.setCreatedAtTime(System.currentTimeMillis() + MobiComUserPreference.getInstance(getActivity()).getDeviceTimeOffset());
                conversationService.sendMessage(messageToResend, messageIntentClass);
                break;
            case 3:
                String messageKeyString = message.getKeyString();
                new DeleteConversationAsyncTask(conversationService, message, contact).execute();
                deleteMessageFromDeviceList(messageKeyString);
                break;
            case 4:
                String messageJson = GsonUtils.getJsonFromObject(message, Message.class);
                conversationUIService.startMessageInfoFragment(messageJson);
                break;
            case 5:
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                if (message.getFilePaths() != null) {
                    Uri shareUri;
                    if (Utils.hasNougat()) {
                        shareUri = FileProvider.getUriForFile(getActivity(), getString(R.string.app_id) + ".fileprovider", new File(message.getFilePaths().get(0)));
                    } else {
                        shareUri = Uri.fromFile(new File(message.getFilePaths().get(0)));
                    }
                    shareIntent.setDataAndType(shareUri, "text/x-vcard");
                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    shareIntent.putExtra(Intent.EXTRA_STREAM, shareUri);
                    if (!TextUtils.isEmpty(message.getMessage())) {
                        shareIntent.putExtra(Intent.EXTRA_TEXT, message.getMessage());
                    }
                    shareIntent.setType(FileUtils.getMimeType(new File(message.getFilePaths().get(0))));
                } else {
                    shareIntent.putExtra(Intent.EXTRA_TEXT, message.getMessage());
                    shareIntent.setType("text/plain");
                }
                startActivity(Intent.createChooser(shareIntent, getString(R.string.send_message_to)));
                break;

            case 6://录制视频

                break;

        }
        return true;
    }

    private void startPrizeAnimation() {
        if (!isRunning) {
            isRunning = true;
            final float moveX;
            if (lottery_area.getLeft() < utils.Utils.getWindowDisplay(getActivity()).widthPixels / 2) {
                //sendAnalyticMsg("lottery" + ANALYTIC_VERSION + "_chat_lottery_show");
                moveX = utils.Utils.getWindowDisplay(getActivity()).widthPixels - utils.Utils.dip2px(getActivity().getApplicationContext(), 50);
            } else {
                //sendAnalyticMsg("lottery" + ANALYTIC_VERSION + "_chat_lottery_hidden");
                moveX = -utils.Utils.getWindowDisplay(getActivity()).widthPixels + utils.Utils.dip2px(getActivity().getApplicationContext(), 50);
            }
            //初始化
            Animation translateAnimation = new TranslateAnimation(0, moveX, 0, 0);
            translateAnimation.setDuration(250);
            lottery_area.startAnimation(translateAnimation);
            translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    int left = lottery_area.getLeft() + (int) moveX;
                    int top = lottery_area.getTop();
                    int width = lottery_area.getWidth();
                    int height = lottery_area.getHeight();
                    lottery_area.clearAnimation();
                    lottery_area.layout(left, top, left + width, top + height);
                    if (lottery_area.getLeft() > utils.Utils.getWindowDisplay(getActivity()).widthPixels / 2) {
                        folder.setImageResource(R.mipmap.unfold);
                    } else {
                        folder.setImageResource(R.mipmap.fold);
                    }
                    isRunning = false;
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        if (isFirstIn) {
            isFirstIn = false;
            folder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startPrizeAnimation();
                }
            });
        }

        if (MobiComUserPreference.getInstance(getActivity()).isChannelDeleted()) {
            MobiComUserPreference.getInstance(getActivity()).setDeleteChannel(false);
            if (getActivity().getSupportFragmentManager() != null) {
                getActivity().getSupportFragmentManager().popBackStack();
            }
            return;
        }
        ((ConversationActivity) getActivity()).setChildFragmentLayoutBGToTransparent();
        if (contact != null || channel != null) {
            BroadcastService.currentUserId = contact != null ? contact.getContactIds() : String.valueOf(channel.getKey());
            BroadcastService.currentConversationId = currentConversationId;
            if (BroadcastService.currentUserId != null) {
                String ns = Context.NOTIFICATION_SERVICE;
                NotificationManager nMgr = (NotificationManager) getActivity().getSystemService(ns);
                nMgr.cancel(BroadcastService.currentUserId.hashCode());
            }

            Intent intent = new Intent(getActivity(), ApplozicMqttIntentService.class);
            intent.putExtra(ApplozicMqttIntentService.CHANNEL, channel);
            intent.putExtra(ApplozicMqttIntentService.SUBSCRIBE_TO_TYPING, true);
            getActivity().startService(intent);

            if (downloadConversation != null) {
                downloadConversation.cancel(true);
            }

            if (contact != null) {
                if (contact.isDeleted()) {
                } else {
                }
                contact = appContactService.getContactById(contact.getContactIds());
                if (contact.isBlocked() || contact.isBlockedBy()) {
                } else {
                    updateLastSeenStatus();
                }
            }

            if (SyncCallService.refreshView) {
                messageList.clear();
                SyncCallService.refreshView = false;
            }

            if (channel != null && !ChannelService.getInstance(getActivity()).processIsUserPresentInChannel(channel.getKey())) {
                Channel newChannel = ChannelService.getInstance(getActivity()).getChannelByChannelKey(channel.getKey());
                if (newChannel != null && newChannel.getType() != null && Channel.GroupType.OPEN.getValue().equals(newChannel.getType())) {
                    MobiComUserPreference.getInstance(getActivity()).setNewMessageFlag(true);
                }
            }

            if (messageList.isEmpty()) {
                loadConversation(contact, channel, currentConversationId, null);
            } else if (MobiComUserPreference.getInstance(getActivity()).getNewMessageFlag()) {
                loadnewMessageOnResume(contact, channel, currentConversationId);
            }

            MobiComUserPreference.getInstance(getActivity()).setNewMessageFlag(false);
        }
        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            public void onRefresh() {
                downloadConversation = new DownloadConversation(listView, false, 1, 1, 1, contact, channel, currentConversationId);
                AsyncTaskCompat.executeParallel(downloadConversation);
            }
        });
        if (channel != null) {
//            updateChannelTitle();

            if (channel.getType() != null && !Channel.GroupType.OPEN.getValue().equals(channel.getType())) {
                boolean present = ChannelService.getInstance(getActivity()).processIsUserPresentInChannel(channel.getKey());
                hideSendMessageLayout(channel.isDeleted() || !present);

            } else {
                hideSendMessageLayout(channel.isDeleted());
            }
            if (ChannelService.isUpdateTitle) {
                updateChannelSubTitle();
                ChannelService.isUpdateTitle = false;
            }
        }

    }

    private void hideSendMessageLayout(boolean hide) {
        if (hide) {
        } else {
        }
    }

    public void updateChannelTitleAndSubTitle() {
        if (channel != null) {
            Channel channelInfo = ChannelService.getInstance(getActivity()).getChannelInfo(channel.getKey());
            if (channelInfo != null) {
                if (channelInfo.isDeleted()) {
                    channel.setDeletedAtTime(channelInfo.getDeletedAtTime());
                } else {
                    if ((!ChannelService.getInstance(getActivity()).processIsUserPresentInChannel(channel.getKey())
                            && !Channel.GroupType.OPEN.getValue().equals(channel.getType()))) {
                    }
                }
            }

//            updateChannelTitle();
            updateChannelSubTitle();
        }
    }


//    public void updateChannelTitle() {
//        if (!Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType())) {
//            Channel newChannel = ChannelService.getInstance(getActivity()).getChannelByChannelKey(channel.getKey());
//            if (newChannel != null && !TextUtils.isEmpty(channel.getName()) && !channel.getName().equals(newChannel.getName())) {
//                title = ChannelUtils.getChannelTitleName(newChannel, MobiComUserPreference.getInstance(getActivity()).getUserId());
//                channel = newChannel;
//                if (title != null && !title.equals("null")) {
//                    boolean isSingle = getActivity().getIntent().getBooleanExtra("is_single", false);
//                    if (!isSingle && roomCount != 0) {
//                        ((TextView) (getActivity()).findViewById(R.id.group_name)).setText(title + "(" + roomCount + ")");
//                    } else {
//                        ((TextView) (getActivity()).findViewById(R.id.group_name)).setText(title);
//                    }
//                }
//            }
//        }
//    }

//    public void updateTitleForOpenGroup() {
//        try {
//            if (channel != null) {
//                Channel newChannel = ChannelService.getInstance(getActivity()).getChannelByChannelKey(channel.getKey());
//                if (newChannel.getName() != null && !newChannel.getName().equals("null")) {
//
//                    boolean isSingle = getActivity().getIntent().getBooleanExtra("is_single", false);
//                    if (!isSingle && roomCount != 0) {
//                        ((TextView) (getActivity()).findViewById(R.id.group_name)).setText(title + "(" + roomCount + ")");
//                    } else {
//                        ((TextView) (getActivity()).findViewById(R.id.group_name)).setText(title);
//                    }
//                }
//            }
//            updateChannelSubTitle();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public void selfDestructMessage(Message message) {
        if (Message.MessageType.MT_INBOX.getValue().equals(message.getType()) &&
                message.getTimeToLive() != null && message.getTimeToLive() != 0) {
            new Timer().schedule(new DisappearingMessageTask(getActivity(), conversationService, message), message.getTimeToLive() * 60 * 1000);
        }
    }

    public void loadnewMessageOnResume(Contact contact, Channel channel, Integer conversationId) {
        downloadConversation = new DownloadConversation(listView, true, 1, 0, 0, contact, channel, conversationId);
        downloadConversation.execute();
    }

    public int ScrollToFirstSearchIndex() {

        int position;
        if (searchString != null) {

            for (position = messageList.size() - 1; position >= 0; position--) {
                Message message = messageList.get(position);
                if (!TextUtils.isEmpty(message.getMessage()) && message.getMessage().toLowerCase(Locale.getDefault()).contains(searchString.toLowerCase(Locale.getDefault()))) {
                    return position;
                }
            }
        } else {
            position = messageList.size();
        }
        return position;
    }

    public void blockUserProcess(final String userId, final boolean block, final boolean isFromChannel) {

        final ProgressDialog progressDialog = ProgressDialog.show(getActivity(), "",
                getActivity().getString(R.string.please_wait_info), true);

        UserBlockTask.TaskListener listener = new UserBlockTask.TaskListener() {

            @Override
            public void onSuccess(ApiResponse apiResponse) {
                if (block && typingStarted) {
                    Intent intent = new Intent(getActivity(), ApplozicMqttIntentService.class);
                    intent.putExtra(ApplozicMqttIntentService.CONTACT, contact);
                    intent.putExtra(ApplozicMqttIntentService.STOP_TYPING, true);
                    getActivity().startService(intent);
                }
                menu.findItem(R.id.userBlock).setVisible(!block);
                menu.findItem(R.id.userUnBlock).setVisible(block);
            }

            @Override
            public void onFailure(ApiResponse apiResponse, Exception exception) {
                String error = getString(Utils.isInternetAvailable(getActivity()) ? R.string.applozic_server_error : R.string.you_need_network_access_for_block_or_unblock);
                Toast toast = Toast.makeText(getActivity(), error, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }

            @Override
            public void onCompletion() {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (!isFromChannel) {
                    contact = appContactService.getContactById(userId);
                }
            }

        };

        new UserBlockTask(getActivity(), listener, userId, block).execute((Void) null);
    }

    public void userBlockDialog(final boolean block, final Contact withUserContact, final boolean isFromChannel) {
        if (withUserContact == null) {
            return;
        }
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity()).
                setPositiveButton(R.string.ok_alert, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        blockUserProcess(withUserContact.getUserId(), block, isFromChannel);
                    }
                });
        alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            }
        });
        String name = withUserContact.getDisplayName();
        alertDialog.setMessage(getString(block ? R.string.user_block_info : R.string.user_un_block_info).replace("[name]", name));
        alertDialog.setCancelable(true);
        alertDialog.create().show();
    }

    public void muteGroupChat() {

        final CharSequence[] items = {getString(R.string.eight_Hours), getString(R.string.one_week), getString(R.string.one_year)};
        Date date = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime();
        millisecond = date.getTime();

        final MuteNotificationAsync.TaskListener taskListener = new MuteNotificationAsync.TaskListener() {
            @Override
            public void onSuccess(ApiResponse apiResponse) {
                if (menu != null) {
                    menu.findItem(R.id.muteGroup).setVisible(false);
                    menu.findItem(R.id.unmuteGroup).setVisible(true);
                }
            }

            @Override
            public void onFailure(ApiResponse apiResponse, Exception exception) {

            }

            @Override
            public void onCompletion() {

            }
        };

        AlertDialog.Builder builder = new AlertDialog.Builder(getContext())
                .setTitle(getResources().getString(R.string.mute_group_for))
                .setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, final int selectedItem) {
                        switch (selectedItem) {
                            case 0:
                                millisecond = millisecond + 28800000;
                                break;
                            case 1:
                                millisecond = millisecond + 604800000;

                                break;
                            case 2:
                                millisecond = millisecond + 31558000000L;
                                break;
                        }

                        muteNotificationRequest = new MuteNotificationRequest(channel.getKey(), millisecond);
                        MuteNotificationAsync muteNotificationAsync = new MuteNotificationAsync(getContext(), taskListener, muteNotificationRequest);
                        muteNotificationAsync.execute((Void) null);
                        dialog.dismiss();

                    }
                });
        AlertDialog alertdialog = builder.create();
        alertdialog.show();
    }

    public void umuteGroupChat() {
        Date date = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime();
        millisecond = date.getTime();

        final MuteNotificationAsync.TaskListener taskListener = new MuteNotificationAsync.TaskListener() {
            @Override
            public void onSuccess(ApiResponse apiResponse) {
                if (menu != null) {
                    menu.findItem(R.id.unmuteGroup).setVisible(false);
                    menu.findItem(R.id.muteGroup).setVisible(true);
                }
            }

            @Override
            public void onFailure(ApiResponse apiResponse, Exception exception) {

            }

            @Override
            public void onCompletion() {

            }
        };
        muteNotificationRequest = new MuteNotificationRequest(channel.getKey(), millisecond);
        MuteNotificationAsync muteNotificationAsync = new MuteNotificationAsync(getContext(), taskListener, muteNotificationRequest);
        muteNotificationAsync.execute((Void) null);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        count = 0;
        ((ConversationActivity) getActivity()).setChildFragmentLayoutBG();
        if (ApplozicAudioManager.getInstance(getContext()) != null) {
            ApplozicAudioManager.getInstance(getContext()).audiostop();
        }

        if (disposable != null) {
            disposable.dispose();
        }
    }

    public ViewGroup.LayoutParams getImageLayoutParam(boolean outBoxType) {
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(metrics);
        float wt_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 60, getActivity().getResources().getDisplayMetrics());
        ViewGroup.MarginLayoutParams params;
        if (outBoxType) {
            params = new RelativeLayout.LayoutParams(metrics.widthPixels + (int) wt_px * 2, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins((int) wt_px, 0, (int) wt_px, 0);
        } else {
            params = new LinearLayout.LayoutParams(metrics.widthPixels - (int) wt_px * 2, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(0, 0, 0, 0);
        }
        return params;
    }

    public class DownloadConversation extends AsyncTask<Void, Integer, Long> {

        private AbsListView view;
        private int firstVisibleItem;
        private int amountVisible;
        private int totalItems;
        private boolean initial;
        private Contact contact;
        private Channel channel;
        private Integer conversationId;
        private List<Conversation> conversationList;
        private List<Message> nextMessageList = new ArrayList<>();

        public DownloadConversation(AbsListView view, boolean initial, int firstVisibleItem, int amountVisible, int totalItems, Contact contact, Channel channel, Integer conversationId) {
            this.view = view;
            this.initial = initial;
            this.firstVisibleItem = firstVisibleItem;
            this.amountVisible = amountVisible;
            this.totalItems = totalItems;
            this.contact = contact;
            this.channel = channel;
            this.conversationId = conversationId;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            emptyTextView.setVisibility(GONE);
            swipeLayout.post(new Runnable() {
                @Override
                public void run() {
                    swipeLayout.setRefreshing(true);
                }
            });
            if (initial) {
                if (recordButtonWeakReference != null) {
                    ImageView recordButton = recordButtonWeakReference.get();
                    if (recordButton != null) {
                        recordButton.setEnabled(false);
                    }
                }
                mySendButton.setEnabled(false);
                myMessageEditText.setEnabled(false);
            }

            if (!initial && messageList.isEmpty()) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity()).
                        setPositiveButton(R.string.ok_alert, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        });
                alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        loadMore = false;
                    }
                });
                //Todo: Move this to mobitexter app
                alertDialog.setTitle(R.string.sync_older_messages);
                alertDialog.setCancelable(true);
                alertDialog.create().show();
            }
        }

        @Override
        protected Long doInBackground(Void... voids) {
            try {
                if (initial) {
                    Long lastConversationloadTime = 1L;
                    if (!messageList.isEmpty()) {
                        for (int i = messageList.size() - 1; i >= 0; i--) {
                            if (messageList.get(i).isTempDateType()) {
                                continue;
                            }
                            lastConversationloadTime = messageList.get(i).getCreatedAtTime();
                            break;
                        }
                    }


                    nextMessageList = conversationService.getMessages(lastConversationloadTime + 1L, null, contact, channel, conversationId);
                } else if (firstVisibleItem == 1 && loadMore && !messageList.isEmpty()) {
                    loadMore = false;
                    Long endTime = null;
                    for (Message message : messageList) {
                        if (message.isTempDateType()) {
                            continue;
                        }
                        endTime = messageList.get(0).getCreatedAtTime();
                        break;
                    }
                    nextMessageList = conversationService.getMessages(null, endTime, contact, channel, conversationId);
                }
                if (BroadcastService.isContextBasedChatEnabled()) {
                    conversations = ConversationService.getInstance(getActivity()).getConversationList(channel, contact);
                }

                List<Message> createAtMessage = new ArrayList<>();
                if (nextMessageList != null && !nextMessageList.isEmpty()) {
                    Message firstDateMessage = new Message();
                    firstDateMessage.setTempDateType(Short.valueOf("100"));
                    firstDateMessage.setCreatedAtTime(nextMessageList.get(0).getCreatedAtTime());

                    if (initial && !messageList.contains(firstDateMessage)) {
                        createAtMessage.add(firstDateMessage);
                    } else if (!initial) {
                        createAtMessage.add(firstDateMessage);
                        messageList.remove(firstDateMessage);
                    }
                    if (!createAtMessage.contains(nextMessageList.get(0))) {
                        createAtMessage.add(nextMessageList.get(0));
                    }

                    for (int i = 1; i <= nextMessageList.size() - 1; i++) {
                        long dayDifference = DateUtils.daysBetween(new Date(nextMessageList.get(i - 1).getCreatedAtTime()), new Date(nextMessageList.get(i).getCreatedAtTime()));

                        if (dayDifference >= 1) {
                            Message message = new Message();
                            message.setTempDateType(Short.valueOf("100"));
                            message.setCreatedAtTime(nextMessageList.get(i).getCreatedAtTime());
                            if (initial && !messageList.contains(message)) {
                                createAtMessage.add(message);
                            } else if (!initial) {
                                createAtMessage.add(message);
                                messageList.remove(message);
                            }
                        }
                        if (!createAtMessage.contains(nextMessageList.get(i))) {
                            createAtMessage.add(nextMessageList.get(i));
                        }
                    }
                }
                nextMessageList = createAtMessage;
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            return 0L;
        }

        protected void onProgressUpdate(Integer... progress) {
            //setProgressPercent(progress[0]);
        }

        @Override
        protected void onPostExecute(Long result) {
            super.onPostExecute(result);
            //TODO: FIX ME
            swipeLayout.post(new Runnable() {
                @Override
                public void run() {
                    swipeLayout.setRefreshing(true);
                }
            });
            if (nextMessageList.isEmpty()) {
                listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_DISABLED);
            }
            //Note: This is done to avoid duplicates with same timestamp entries
            if (!messageList.isEmpty() && !nextMessageList.isEmpty() &&
                    messageList.get(0).equals(nextMessageList.get(nextMessageList.size() - 1))) {
                nextMessageList.remove(nextMessageList.size() - 1);
            }

            if (!messageList.isEmpty() && !nextMessageList.isEmpty() &&
                    messageList.get(0).getCreatedAtTime().equals(nextMessageList.get(nextMessageList.size() - 1).getCreatedAtTime())) {
                nextMessageList.remove(nextMessageList.size() - 1);
            }

            for (Message message : nextMessageList) {
                selfDestructMessage(message);
            }

            if (initial) {
                messageList.addAll(nextMessageList);
                conversationAdapter.searchString = searchString;
                emptyTextView.setVisibility(messageList.isEmpty() ? VISIBLE : GONE);
                if (!messageList.isEmpty()) {
                    listView.post(new Runnable() {
                        @Override
                        public void run() {
                            if (!TextUtils.isEmpty(searchString)) {
                                int height = listView.getHeight();
                                int itemHeight = listView.getChildAt(0).getHeight();
                                listView.requestFocusFromTouch();
                                listView.setSelectionFromTop(ScrollToFirstSearchIndex() + 1, height / 2 - itemHeight / 2);
                            } else {
                                listView.setSelection(messageList.size() - 1);

                            }
                        }
                    });
                }
            } else if (!nextMessageList.isEmpty()) {
                listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_DISABLED);
                messageList.addAll(0, nextMessageList);
                listView.setSelection(nextMessageList.size());
            }

            conversationService.read(contact, channel);

            if (!messageList.isEmpty()) {
                for (int i = messageList.size() - 1; i >= 0; i--) {
                    Message message = messageList.get(i);
                    if (!message.isRead() && !message.isTempDateType() && !message.isCustom()) {
                        message.setRead(Boolean.TRUE);
                        messageDatabaseService.updateMessageReadFlag(message.getMessageId(), true);
                    } else {
                        break;
                    }
                }
            }

            if (conversations != null && conversations.size() > 0) {
                conversationList = conversations;
            }
            if (conversationList != null && conversationList.size() > 0 && !onSelected) {
                onSelected = true;
            }
            if (conversationAdapter != null) {
                conversationAdapter.notifyDataSetChanged();
            }
            swipeLayout.post(new Runnable() {
                @Override
                public void run() {
                    swipeLayout.setRefreshing(false);
                }
            });

            if (messageToForward != null) {
                sendForwardMessage(messageToForward);
                messageToForward = null;
            }

            if (!messageList.isEmpty()) {
                channelKey = messageList.get(messageList.size() - 1).getGroupId();
            }
            if (initial) {
                if (recordButtonWeakReference != null) {
                    ImageView recordButton = recordButtonWeakReference.get();
                    if (recordButton != null) {
                        recordButton.setEnabled(true);
                    }
                }
                mySendButton.setEnabled(true);
                myMessageEditText.setEnabled(true);
            }
            loadMore = !nextMessageList.isEmpty();
        }
    }

    private void getRoomInfo() {
        RetrofitBase.getRetrofit().create(GetRoomUsersRequest.class)
                .getResult(UserInfo.getToken(), UserInfo.getRoomId() , null, 10, 0)
                .compose(RxHelper.<GetRoomUsersResponse>handleResult())
                .subscribeWith(new RxSubscribe<GetRoomUsersResponse>(getActivity()) {
                    @Override
                    protected void _onNext(GetRoomUsersResponse getRoomUsersResponses) {
                        roomCount = getRoomUsersResponses.getCount();
                        updateTitle();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }
}